<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blogwebpage/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blogwebpage/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/blogwebpage/images/favicon.ico">
  <link rel="mask-icon" href="/blogwebpage/images/logo.svg" color="#222">
  <meta name="msvalidate.01" content="9BDlx6FiNE">

<link rel="stylesheet" href="/blogwebpage/css/main.css">


<link rel="stylesheet" href="/blogwebpage/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangkejie.gitee.io","root":"/blogwebpage/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="书山有路勤为径，学海无涯苦作舟！">
<meta property="og:type" content="website">
<meta property="og:title" content="王科杰">
<meta property="og:url" content="https://wangkejie.gitee.io/blogwebpage/page/3/index.html">
<meta property="og:site_name" content="王科杰">
<meta property="og:description" content="书山有路勤为径，学海无涯苦作舟！">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="Jack Wang">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wangkejie.gitee.io/blogwebpage/page/3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>王科杰 - Jack's Notes</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?93e26277de0cf2c5851167f2c6dcaa7d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blogwebpage/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">王科杰</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Jack's Notes</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blogwebpage/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blogwebpage/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">52</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blogwebpage/me/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blogwebpage/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">54</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blogwebpage/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">56</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/RunLoop/runloop.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/RunLoop/runloop.html" class="post-title-link" itemprop="url">RunLoop的一些场景</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/RunLoop/" itemprop="url" rel="index"><span itemprop="name">RunLoop</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/RunLoop/RunLoop%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9C%BA%E6%99%AF/" itemprop="url" rel="index"><span itemprop="name">RunLoop的一些场景</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="一、autoreleasePool-在何时被释放？"><a href="#一、autoreleasePool-在何时被释放？" class="headerlink" title="一、autoreleasePool 在何时被释放？"></a>一、<code>autoreleasePool</code> 在何时被释放？</h2><p><code>App</code>启动后，苹果在主线程 <code>RunLoop</code> 里注册了两个 <code>Observer</code>，其回调都是 <code>_wrapRunLoopWithAutoreleasePoolHandler()</code>。</p>
<p>第一个 <code>Observer</code> 监视的事件是 <code>Entry(即将进入Loop)</code>，其回调内会调用 <code>_objc_autoreleasePoolPush()</code> 创建自动释放池。其 <code>order</code> 是 <code>-2147483647</code>，优先级最高，保证创建释放池发生在其他所有回调之前。</p>
<p>第二个 <code>Observer</code> 监视了两个事件： <code>BeforeWaiting</code>(准备进入休眠) 时调用<code>_objc_autoreleasePoolPop()</code>  和 <code>_objc_autoreleasePoolPush()</code> 释放旧的池并创建新池；<code>Exit</code>(即将退出Loop) 时调用 <code>_objc_autoreleasePoolPop()</code> 来释放自动释放池。这个 <code>Observer</code> 的 <code>order</code> 是 <code>2147483647</code>，优先级最低，保证其释放池子发生在其他所有回调之后。</p>
<p>在主线程执行的代码，通常是写在诸如事件回调、<code>Timer</code>回调内的。这些回调会被 <code>RunLoop</code> 创建好的 <code>AutoreleasePool</code> 环绕着，所以不会出现内存泄漏，开发者也不必显示创建 <code>Pool</code> 了。</p>
<h2 id="二、PerformSelector-的实现原理？"><a href="#二、PerformSelector-的实现原理？" class="headerlink" title="二、PerformSelector 的实现原理？"></a>二、<code>PerformSelector</code> 的实现原理？</h2><p>当调用 NSObject 的 performSelecter:afterDelay: 后，实际上其内部会创建一个 Timer 并添加到当前线程的 RunLoop 中。所以如果当前线程没有 RunLoop，则这个方法会失效。</p>
<p>当调用 performSelector:onThread: 时，实际上其会创建一个 Timer 加到对应的线程去，同样的，如果对应线程没有 RunLoop 该方法也会失效。</p>
<h2 id="三、PerformSelector-afterDelay-这个方法在子线程中是否起作用？为什么？怎么解决？"><a href="#三、PerformSelector-afterDelay-这个方法在子线程中是否起作用？为什么？怎么解决？" class="headerlink" title="三、PerformSelector:afterDelay:这个方法在子线程中是否起作用？为什么？怎么解决？"></a>三、<code>PerformSelector:afterDelay:</code>这个方法在子线程中是否起作用？为什么？怎么解决？</h2><p>不起作用，子线程默认没有 <code>Runloop</code>，也就没有 <code>Timer</code>。</p>
<p>解决的办法是可以使用 <code>GCD</code> 来实现：<code>Dispatch_after</code></p>
<h2 id="四、为什么-NSTimer-有时候不好使？"><a href="#四、为什么-NSTimer-有时候不好使？" class="headerlink" title="四、为什么 NSTimer 有时候不好使？"></a>四、为什么 <code>NSTimer</code> 有时候不好使？</h2><p>因为创建的  <code>NSTimer</code> 默认是被加入到了 <code>defaultMode</code>，所以当 <code>Runloop</code> 的 <code>Mode</code> 变化时，当前的 <code>NSTimer</code> 就不会工作了。</p>
<h2 id="五、解释一下-GCD-在-Runloop-中的使用？"><a href="#五、解释一下-GCD-在-Runloop-中的使用？" class="headerlink" title="五、解释一下 GCD 在 Runloop 中的使用？"></a>五、解释一下 <code>GCD</code> 在 <code>Runloop</code> 中的使用？</h2><p><code>GCD</code>由 子线程 返回到 主线程,只有在这种情况下才会触发 RunLoop。会触发 RunLoop 的 Source 1 事件。</p>
<h2 id="六、解释一下-NSTimer。"><a href="#六、解释一下-NSTimer。" class="headerlink" title="六、解释一下 NSTimer。"></a>六、解释一下 <code>NSTimer</code>。</h2><p><code>NSTimer</code> 其实就是 <code>CFRunLoopTimerRef</code>，他们之间是 <code>toll-free bridged</code> 的。一个 <code>NSTimer</code> 注册到 <code>RunLoop</code> 后，<code>RunLoop</code> 会为其重复的时间点注册好事件。例如 <code>10:00</code>, <code>10:10</code>, <code>10:20</code> 这几个时间点。<code>RunLoop</code> 为了节省资源，并不会在非常准确的时间点回调这个<code>Timer</code>。<code>Timer</code> 有个属性叫做 <code>Tolerance</code> (宽容度)，标示了当时间点到后，容许有多少最大误差。</p>
<p>如果某个时间点被错过了，例如执行了一个很长的任务，则那个时间点的回调也会跳过去，不会延后执行。就比如等公交，如果 10:10 时我忙着玩手机错过了那个点的公交，那我只能等 10:20 这一趟了。</p>
<p><code>CADisplayLink</code> 是一个和屏幕刷新率一致的定时器（但实际实现原理更复杂，和 NSTimer 并不一样，其内部实际是操作了一个 <code>Source</code>）。如果在两次屏幕刷新之间执行了一个长任务，那其中就会有一帧被跳过去（和 <code>NSTimer</code> 相似），造成界面卡顿的感觉。在快速滑动 <code>TableView</code> 时，即使一帧的卡顿也会让用户有所察觉。<code>Facebook</code> 开源的 <code>AsyncDisplayLink</code> 就是为了解决界面卡顿的问题，其内部也用到了 <code>RunLoop</code>。</p>
<h2 id="七、等待补充中。。。"><a href="#七、等待补充中。。。" class="headerlink" title="七、等待补充中。。。"></a>七、等待补充中。。。</h2>
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/RunTime/index.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/RunTime/index.html" class="post-title-link" itemprop="url">RunTime知识</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/RunTime/" itemprop="url" rel="index"><span itemprop="name">RunTime</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>这里主要收集RunTime相关东西</p>
<h2 id="如何运用-Runtime-进行模型的归解档"><a href="#如何运用-Runtime-进行模型的归解档" class="headerlink" title="如何运用 Runtime 进行模型的归解档"></a>如何运用 <code>Runtime</code> 进行模型的归解档</h2><p><code>Runtime</code> 遍历 <code>ivar_list</code>。</p>
<h2 id="如何运用-Runtime-字典转模型？"><a href="#如何运用-Runtime-字典转模型？" class="headerlink" title="如何运用 Runtime 字典转模型？"></a>如何运用 <code>Runtime</code> 字典转模型？</h2><p><code>Runtime</code> 遍历 <code>ivar_list</code>,结合 <code>KVC</code> 赋值。</p>
<h2 id="如何给-Category-添加属性？关联对象以什么形式进行存储？"><a href="#如何给-Category-添加属性？关联对象以什么形式进行存储？" class="headerlink" title="如何给 Category 添加属性？关联对象以什么形式进行存储？"></a>如何给 <code>Category</code> 添加属性？关联对象以什么形式进行存储？</h2><p>查看的是 <code>关联对象</code> 的知识点。</p>
<p>详细的说一下 <code>关联对象</code>。<br><code>关联对象</code> 以哈希表的格式，存储在一个全局的单例中。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">NSObject</span> (<span class="title">Extension</span>)</span></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>,<span class="keyword">copy</span>  ) <span class="built_in">NSString</span> *name;</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">NSObject</span> (<span class="title">Extension</span>)</span></span><br><span class="line"></span><br><span class="line">- (<span class="keyword">void</span>)setName:(<span class="built_in">NSString</span> *)name &#123;</span><br><span class="line">    </span><br><span class="line">    objc_setAssociatedObject(<span class="keyword">self</span>, <span class="keyword">@selector</span>(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);</span><br><span class="line">&#125;</span><br><span class="line">- (<span class="built_in">NSString</span> *)name &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> objc_getAssociatedObject(<span class="keyword">self</span>,<span class="keyword">@selector</span>(name));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<h2 id="什么时候会报unrecognized-selector的异常？"><a href="#什么时候会报unrecognized-selector的异常？" class="headerlink" title="什么时候会报unrecognized selector的异常？"></a>什么时候会报unrecognized selector的异常？</h2><p>objc在向一个对象发送消息时，runtime库会根据对象的isa指针找到该对象实际所属的类，然后在该类中的方法列表以及其父类方法列表中寻找方法运行，如果，在最顶层的父类中依然找不到相应的方法时，会进入消息转发阶段，如果消息三次转发流程仍未实现，则程序在运行时会挂掉并抛出异常unrecognized selector sent to XXX 。</p>
<h2 id="runtime如何实现weak变量的自动置nil？知道SideTable吗？"><a href="#runtime如何实现weak变量的自动置nil？知道SideTable吗？" class="headerlink" title="runtime如何实现weak变量的自动置nil？知道SideTable吗？"></a>runtime如何实现weak变量的自动置nil？知道SideTable吗？</h2><blockquote>
<p>runtime 对注册的类会进行布局，对于 weak 修饰的对象会放入一个 hash 表中。 用 weak 指向的对象内存地址作为key，当此对象的引用计数为0的时候会 dealloc，假如 weak 指向的对象内存地址是a，那么就会以a为键， 在这个 weak表中搜索，找到所有以a为键的 weak 对象，从而设置为 nil。</p>
</blockquote>
<p><strong>更细一点的回答：</strong></p>
<p>1.初始化时：runtime会调用objc_initWeak函数，初始化一个新的weak指针指向对象的地址。<br>2.添加引用时：objc_initWeak函数会调用objc_storeWeak() 函数， objc_storeWeak()的作用是更新指针指向，创建对应的弱引用表。<br>3.释放时,调用clearDeallocating函数。clearDeallocating函数首先根据对象地址获取所有weak指针地址的数组，然后遍历这个数组把其中的数据设为nil，最后把这个entry从weak表中删除，最后清理对象的记录。</p>
<p>SideTable结构体是负责管理类的引用计数表和weak表，</p>
<p>详解：参考自《Objective-C高级编程》一书<br><strong>1.初始化时：runtime会调用objc_initWeak函数，初始化一个新的weak指针指向对象的地址。</strong></p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="built_in">NSObject</span> *obj = [[<span class="built_in">NSObject</span> alloc] init];</span><br><span class="line">    <span class="keyword">id</span> __<span class="keyword">weak</span> obj1 = obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当我们初始化一个weak变量时，runtime会调用 NSObject.mm 中的objc_initWeak函数。</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 编译器的模拟代码</span></span><br><span class="line"> id obj1;</span><br><span class="line"> objc<span class="constructor">_initWeak(&amp;<span class="params">obj1</span>, <span class="params">obj</span>)</span>;</span><br><span class="line"><span class="comment">/*obj引用计数变为0，变量作用域结束*/</span></span><br><span class="line"> objc<span class="constructor">_destroyWeak(&amp;<span class="params">obj1</span>)</span>;</span><br></pre></td></tr></table></figure>
<p>通过objc_initWeak函数初始化“附有weak修饰符的变量（obj1）”，在变量作用域结束时通过objc_destoryWeak函数释放该变量（obj1）。</p>
<p><strong>2.添加引用时：objc_initWeak函数会调用objc_storeWeak() 函数， objc_storeWeak()的作用是更新指针指向，创建对应的弱引用表。</strong></p>
<p>objc_initWeak函数将“附有weak修饰符的变量（obj1）”初始化为0（nil）后，会将“赋值对象”（obj）作为参数，调用objc_storeWeak函数。</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">obj1 = <span class="number">0</span>；</span><br><span class="line">obj<span class="constructor">_storeWeak(&amp;<span class="params">obj1</span>, <span class="params">obj</span>)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>也就是说：</strong></p>
<p>weak 修饰的指针默认值是 nil （在Objective-C中向nil发送消息是安全的）</p>
<p>然后obj_destroyWeak函数将0（nil）作为参数，调用objc_storeWeak函数。</p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">objc_storeWeak</span>(&amp;obj<span class="number">1</span>, <span class="number">0</span>);</span><br></pre></td></tr></table></figure>
<p>前面的源代码与下列源代码相同。</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 编译器的模拟代码</span></span><br><span class="line">id obj1;</span><br><span class="line">obj1 = <span class="number">0</span>;</span><br><span class="line">objc<span class="constructor">_storeWeak(&amp;<span class="params">obj1</span>, <span class="params">obj</span>)</span>;</span><br><span class="line"><span class="comment">/* ... obj的引用计数变为0，被置nil ... */</span></span><br><span class="line">objc<span class="constructor">_storeWeak(&amp;<span class="params">obj1</span>, 0)</span>;</span><br></pre></td></tr></table></figure>
<p>objc_storeWeak函数把第二个参数的赋值对象（obj）的内存地址作为键值，将第一个参数__weak修饰的属性变量（obj1）的内存地址注册到 weak 表中。如果第二个参数（obj）为0（nil），那么把变量（obj1）的地址从weak表中删除。</p>
<p>由于一个对象可同时赋值给多个附有__weak修饰符的变量中，所以对于一个键值，可注册多个变量的地址。</p>
<p>可以把objc_storeWeak(&amp;a, b)理解为：objc_storeWeak(value, key)，并且当key变nil，将value置nil。在b非nil时，a和b指向同一个内存地址，在b变nil时，a变nil。此时向a发送消息不会崩溃：在Objective-C中向nil发送消息是安全的。</p>
<p><strong>3.释放时,调用clearDeallocating函数。clearDeallocating函数首先根据对象地址获取所有weak指针地址的数组，然后遍历这个数组把其中的数据设为nil，最后把这个entry从weak表中删除，最后清理对象的记录。</strong></p>
<p>当weak引用指向的对象被释放时，又是如何去处理weak指针的呢？当释放对象时，其基本流程如下：</p>
<p>1.调用objc_release<br>2.因为对象的引用计数为0，所以执行dealloc<br>3.在dealloc中，调用了_objc_rootDealloc函数<br>4.在_objc_rootDealloc中，调用了object_dispose函数<br>5.调用objc_destructInstance<br>6.最后调用objc_clear_deallocating</p>
<p>对象被释放时调用的objc_clear_deallocating函数:</p>
<p>1.从weak表中获取废弃对象的地址为键值的记录<br>2.将包含在记录中的所有附有 weak修饰符变量的地址，赋值为nil<br>3.将weak表中该记录删除<br>4.从引用计数表中删除废弃对象的地址为键值的记录</p>
<p><strong>总结:</strong></p>
<p>其实Weak表是一个hash（哈希）表，Key是weak所指对象的地址，Value是weak指针的地址（这个地址的值是所指对象指针的地址）数组。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/ScrollView/index.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/ScrollView/index.html" class="post-title-link" itemprop="url">scrollView左右上下单方向滑动下问题</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="解决iOS的scrollView属性directionalLockEnabled的问题修正"><a href="#解决iOS的scrollView属性directionalLockEnabled的问题修正" class="headerlink" title="解决iOS的scrollView属性directionalLockEnabled的问题修正"></a>解决iOS的scrollView属性directionalLockEnabled的问题修正</h1><p>苹果官方文档说明</p>
<blockquote>
<p>“If this property is NO, scrolling is permitted in both horizontal and vertical directions. If this property is YES and the user begins dragging in one general direction (horizontally or vertically), the scroll view disables scrolling in the other direction. If the drag direction is diagonal, then scrolling will not be locked and the user can drag in any direction<br>until the drag completes. The default value is NO”</p>
</blockquote>
<p>问题出现了，当你斜着滑动的时候，这个属性就失效了，就会出现斜着滑动的情况</p>
<h2 id="解决办法如下："><a href="#解决办法如下：" class="headerlink" title="解决办法如下："></a>解决办法如下：</h2>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/blogwebpage/iOS/ScrollView/index.html#more" rel="contents">
                阅读全文 &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/designpatten/index.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/designpatten/index.html" class="post-title-link" itemprop="url">iOS设计模式</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">iOS设计模式</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="一、编程中的六大设计原则？"><a href="#一、编程中的六大设计原则？" class="headerlink" title="一、编程中的六大设计原则？"></a>一、编程中的六大设计原则？</h2><h3 id="1-单一职责原则"><a href="#1-单一职责原则" class="headerlink" title="1.单一职责原则"></a>1.单一职责原则</h3><p>通俗地讲就是一个类只做一件事</p>
<ul>
<li><code>CALayer</code>：动画和视图的显示。</li>
<li><code>UIView</code>：只负责事件传递、事件响应。</li>
</ul>
<h3 id="2-开闭原则"><a href="#2-开闭原则" class="headerlink" title="2.开闭原则"></a>2.开闭原则</h3><p>对修改关闭，对扩展开放。<br>要考虑到后续的扩展性，而不是在原有的基础上来回修改</p>
<h3 id="3-接口隔离原则"><a href="#3-接口隔离原则" class="headerlink" title="3.接口隔离原则"></a>3.接口隔离原则</h3><p>使用多个专门的协议、而不是一个庞大臃肿的协议</p>
<ul>
<li><code>UITableviewDelegate</code></li>
<li><code>UITableViewDataSource</code></li>
</ul>
<h3 id="4-依赖倒置原则"><a href="#4-依赖倒置原则" class="headerlink" title="4.依赖倒置原则"></a>4.依赖倒置原则</h3><p>抽象不应该依赖于具体实现、具体实现可以依赖于抽象。<br>调用接口感觉不到内部是如何操作的</p>
<h3 id="5-里氏替换原则"><a href="#5-里氏替换原则" class="headerlink" title="5.里氏替换原则"></a>5.里氏替换原则</h3><p>父类可以被子类无缝替换，且原有的功能不受任何影响</p>
<p>例如 KVO</p>
<h3 id="6-迪米特法则"><a href="#6-迪米特法则" class="headerlink" title="6.迪米特法则"></a>6.迪米特法则</h3><p>一个对象应当对其他对象尽可能少的了解，实现高聚合、低耦合</p>
<h1 id="推荐文章"><a href="#推荐文章" class="headerlink" title="推荐文章"></a>推荐文章</h1><p><span class="exturl" data-url="aHR0cHM6Ly9qdWVqaW4uaW0vcG9zdC81Yjk1MjZjMWU1MWQ0NTBlNjk3MzFkYzI=">面向对象设计的六大设计原则（附 Demo 及 UML 类图）- J_Knight_<i class="fa fa-external-link-alt"></i></span></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/interview/apppackage.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/interview/apppackage.html" class="post-title-link" itemprop="url">iOS_App_包优化</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/app-%E5%8C%85%E4%BC%98%E5%8C%96/" itemprop="url" rel="index"><span itemprop="name">app 包优化</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>App安装包（ipa文件）是由资源（图片+文档）和可执行文件（二进制文件）两部分组成，安装包瘦身也是从这两部分进行。</p>
<h2 id="图片"><a href="#图片" class="headerlink" title="图片"></a>图片</h2><p>图片基本来说在打包完成后，被压缩很少的，听从苹果的建议，使用 png，并且放到<code>Assets.xcassets</code>目录里面<br>删除无用的图片.  LSUnusedResource软件   </p>
<ul>
<li><p>On Demand Resource<br>苹果从iOS 9开始引入了On Demand Resource功能，即一部分图片可以被放置在苹果的服务器上，不随着app的下载而下载，直到用户真正进入到某个页面时才下载这些资源文件。<br>我们考虑可以让某些业务仅在iOS 9及以后版本中可用，然后应用On Demand Resource来优化这些业务的资源。<br>经过了一段时间的开发实验，一切都如同预期，当我们以为On Demand Resource是一个可行的思路时，我们却发现了一个Xcode巨坑的问题：当工程需要支持iOS9以下系统时，Xcode会在打包完成上传app store时失败。On Demand Resource的想法只能搁置。</p>
</li>
<li><p>修复cocoapods带来的图片重复合并问题, 参考今日头条团队的文章（下文提到）</p>
</li>
<li><p>使用tint color</p>
</li>
</ul>
<h2 id="资源文件"><a href="#资源文件" class="headerlink" title="资源文件"></a>资源文件</h2><p>一定要注意，资源文件是否需要编译进入工程，特别是 readme 这种的，不要编译进项目</p>
<h2 id="Xcode编译选项优化："><a href="#Xcode编译选项优化：" class="headerlink" title="Xcode编译选项优化："></a>Xcode编译选项优化：</h2><ul>
<li>build setting 里 DEAD_CODE_STRIPPING = YES（好像默认就是YES）。 确定 dead code（代码被定义但从未被调用）被剥离，去掉冗余的代码，即使一点冗余代码，编译后体积也是很可观的。</li>
<li>Build Settings-&gt;Optimization Level有几个编译优化选项，release版应该选择Fastest, Smalllest[-Os]，这个选项会开启那些不增加代码大小的全部优化，并让可执行文件尽可能小。</li>
<li>Strip Debug Symbols During Copy 和 Symbols Hidden by Default 在release版本应该设为yes，可以去除不必要的调试符号。Symbols Hidden by Default会把所有符号都定义成”private extern”，设了后会减小体积。</li>
<li>Strip Linked Product：DEBUG下设为NO，RELEASE下设为YES，用于RELEASE模式下缩减app的大小；</li>
</ul>
<blockquote>
<p>另外注意Xcode里面的Deployment选项,Deployment Postprocessing这个配置项如果使用xcode打包，xcode会默认把这个变量置为YES， 如果使用脚本打包，记得设置。Symbols Hidden by Default设置为YES Make Strings Read-Only 设置为YES</p>
</blockquote>
<ul>
<li>编译选项：LTO，即Link Time Optimization。</li>
</ul>
<p>苹果在2016年的WWDC What’s new in LLVM中详细介绍了这一功能。LTO能带来的优化有：<br>（1）将一些函数內联化<br>（2）去除了一些无用代码<br>（3）对程序有全局的优化作用<br>在build setting中开启Link-Time Optimization为Incremental，经测试可缩减安装包大小500KB左右。苹果还声称LTO对app的运行速度也有正向帮助。<br>但LTO也会带来一点副作用。LTO会降低编译链接的速度，因此只建议在打正式包时开启；开启了LTO之后，link map的可读性明显降低，多出了很多数字开头的“类”（LTO的全局优化导致的），导致我们还经常需要手动关闭LTO打包来阅读link map。</p>
<h2 id="启动速度优化"><a href="#启动速度优化" class="headerlink" title="启动速度优化"></a>启动速度优化</h2><h3 id="main-调用之前的耗时我们可以优化的点有："><a href="#main-调用之前的耗时我们可以优化的点有：" class="headerlink" title="main()调用之前的耗时我们可以优化的点有："></a>main()调用之前的耗时我们可以优化的点有：</h3><ul>
<li>减少不必要的framework，因为动态链接比较耗时</li>
<li>check framework应当设为 optional 和 required ，如果该framework在当前App支持的所有- iOS系统版本都存在，那么就设为required，否则就设为 optional，因为 optional 会有些额外的检查</li>
<li>合并或者删减一些OC类，关于清理项目中没用到的类，使用工具AppCode代码检查功能</li>
<li>删减一些无用的静态变量</li>
<li>删减没有被调用到或者已经废弃的方法 <code>-Wall -Wextra -Weverything</code> Other Warning Flags</li>
<li>将不必须在 +load 方法中做的事情延迟到 +initialize 中</li>
<li>尽量不要用 C++ 虚函数(创建虚函数表有开销)</li>
</ul>
<h3 id="main-调用之后的加载时间"><a href="#main-调用之后的加载时间" class="headerlink" title="main()调用之后的加载时间"></a>main()调用之后的加载时间</h3><ul>
<li><p>分析<br>在main()被调用之后，App的主要工作就是初始化必要的服务，显示首页内容等。而我们的优化也是围绕如何能够快速展现首页来开展。<br>App通常在 AppDelegate 类中的didFinishLaunchingWithOptions: 方法中创建首页需要展示的view，然后在当前runloop的末尾，主动调用CA::Transaction::commit完成视图的渲染。</p>
</li>
<li><p>而视图的渲染主要涉及三个阶段：</p>
<ol>
<li>准备阶段 这里主要是图片的解码</li>
<li>布局阶段 首页所有UIView的 layoutSubViews 运行</li>
<li>绘制阶段 首页所有UIView的 drawRect: 运行</li>
<li>再加上启动之后必要服务的启动、必要数据的创建和读取，这些就是我们可以尝试优化的地方</li>
</ol>
</li>
<li><p>main()函数调用之后可以优化的点：</p>
<ul>
<li>不使用是storyboard、xib，直接视用代码加载首页视图</li>
<li>NSUserDefaults实际上是在Library文件夹下会生产一个plist文件，如果文件太大的话一次能读取到内存中可能很耗时，这个影响需要评估，如果耗时很大的话需要拆分(需考虑老版本覆盖安装兼容问题)</li>
<li>每次用NSLog方式打印会隐式的创建一个Calendar，因此需要删减启动时各业务方打的log，或者仅仅针对内测版输出log</li>
<li>梳理应用启动时发送的所有网络请求，是否可以统一在异步线程请求</li>
</ul>
</li>
</ul>
<h2 id="下面引用-今日头条团队优化"><a href="#下面引用-今日头条团队优化" class="headerlink" title="下面引用 今日头条团队优化"></a>下面引用 今日头条团队优化</h2><p><span class="exturl" data-url="aHR0cHM6Ly93d3cuamlhbnNodS5jb20vcC9hMzE1MWRmZWJjOWM=">干货|今日头条iOS端安装包大小优化—思路与实践<i class="fa fa-external-link-alt"></i></span></p>
<h3 id="分析link-map"><a href="#分析link-map" class="headerlink" title="分析link map"></a>分析link map</h3><p>link map是编译链接时可以生成的一个txt文件，它生成目的就是帮助程序员分析包大小。link map记录了每个方法在当前的二进制架构下占据的空间。通过分析link map，我们可以了解每个类甚至每个方法占据了多少安装包空间。<br>在编译时开启Xcode build setting中的Write Link Map File开关，Xcode就会生成一份link map文件。<br>目前已经有不少开源的分析link map的工具，可以输出每个类、每个静态库占用的空间，并进行排序。通过查看link map，我们可以对二进制代码占据的包大小空间有个直观了解，同时在引入第三方库时也可以使用link map作出评估。</p>
<h3 id="如何进行二进制文件优化"><a href="#如何进行二进制文件优化" class="headerlink" title="如何进行二进制文件优化"></a>如何进行二进制文件优化</h3><h4 id="技术手段排查冗余代码"><a href="#技术手段排查冗余代码" class="headerlink" title="技术手段排查冗余代码"></a>技术手段排查冗余代码</h4><p>没有被引用的类和方法是可以通过技术手段被筛选出来的。<br>MachO文件中有__DATA.__objc_classrefs和__DATA.__objc_selrefs段，分别近似于“被使用的类的集合”和“被使用的方法的集合”。通过取差集的方式可以筛选出未被使用的类和方法。</p>
<h4 id="排查无用类"><a href="#排查无用类" class="headerlink" title="排查无用类"></a>排查无用类</h4><p>使用otool命令可查看__DATA.__objc_classrefs段和__DATA.__objc_classlist段，两者的差集可以认为是定义了但未使用的类。<br>不过__DATA.__objc_classrefs段和__DATA.__objc_classlist段中都只提供了类在二进制文件中的位置地址，而没有提供类名等可读信息。所以在获取到差集后，还需要结合</p>
<blockquote>
<p>otool -o BinaryName</p>
</blockquote>
<p>命令的输出，将地址转换成可读的类名。</p>
<p>使用脚本筛选出差集对应的类后，还需要进行一遍人工选择。因为动态使用的类、从nib或storyboard初始化的类以及在同一个文件中定义的多个类会被误判为未使用的类。这需要结合业务进行一次梳理。</p>
<h4 id="排查无用方法"><a href="#排查无用方法" class="headerlink" title="排查无用方法"></a>排查无用方法</h4><p>所有已经被实现的方法可以通过linkmap来获取，对linkmap做grep操作即可获得结果：</p>
<blockquote>
<p><code>grep &#39;[+|-]\[.*\s.*\]&#39;</code></p>
</blockquote>
<p>而所有已经被使用的方法可以通过对二进制文件逆向获得。使用otool工具逆向二进制文件的__DATA.__objc_selrefs 段，提取可执行文件里引用到的方法名：</p>
<blockquote>
<p>otool -v -s __DATA __objc_selrefs</p>
</blockquote>
<p>使用这种方法取到的差集，还需要排除掉系统API中的protocol，accessor方法等。</p>
<p>使用这个方法，头条排查出了无用方法2000余个，总共累积约2MB，其中最长的方法约7KB。考虑到删除方法的工作量和风险都相对较大，目前我们仅对其中很小一部分进行了删除。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/interview/delegate.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/interview/delegate.html" class="post-title-link" itemprop="url">HTTP 代理原理</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/HTTP-%E4%BB%A3%E7%90%86%E5%8E%9F%E7%90%86/" itemprop="url" rel="index"><span itemprop="name">HTTP 代理原理</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>HTTP 代理存在两种形式:<br>第一种是 RFC 7230 - HTTP/1.1: Message Syntax and Routing（即修订后的 RFC 2616，HTTP/1.1 协议的第一部分）描述的普通代理。这种代理扮演的是「中间人」角色，对于连接到它的客户端来说，它是服务端；对于要连接的服务端来说，它是客户端。它就负责在两端之间来回传送 HTTP 报文。</p>
<p>第二种是 Tunneling TCP based protocols through Web proxy servers（通过 Web 代理服务器用隧道方式传输基于 TCP 的协议）描述的隧道代理。它通过 HTTP 协议正文部分（Body）完成通讯，以 HTTP 的方式实现任意基于 TCP 的应用层协议代理。这种代理使用 HTTP 的 CONNECT 方法建立连接，但 CONNECT 最开始并不是 RFC 2616 - HTTP/1.1 的一部分，直到 2014 年发布的 HTTP/1.1 修订版中，才增加了对 CONNECT 及隧道代理的描述，详见 RFC 7231 - HTTP/1.1: Semantics and Content。实际上这种代理早就被广泛实现。</p>
<p>本文描述的第一种代理，对应《HTTP 权威指南》一书中第六章「代理」；第二种代理，对应第八章「集成点：网关、隧道及中继」中的 8.5 小节「隧道」。</p>
<h2 id="第一种-Web-代理原理特别简单："><a href="#第一种-Web-代理原理特别简单：" class="headerlink" title="第一种 Web 代理原理特别简单："></a>第一种 Web 代理原理特别简单：</h2><blockquote>
<p>HTTP 客户端向代理发送请求报文，代理服务器需要正确地处理请求和连接（例如正确处理 Connection: keep-alive），同时向服务器发送请求，并将收到的响应转发给客户端。</p>
</blockquote>
<img src="/blogwebpage/images/iOS/web_proxy.jpeg" class="" title="web_proxy">

<p>假如我通过代理访问 A 网站，对于 A 来说，它会把代理当做客户端，完全察觉不到真正客户端的存在，这实现了隐藏客户端 IP 的目的。当然代理也可以修改 HTTP 请求头部，通过 X-Forwarded-IP 这样的自定义头部告诉服务端真正的客户端 IP。但服务器无法验证这个自定义头部真的是由代理添加，还是客户端修改了请求头，所以从 HTTP 头部字段获取 IP 时，需要格外小心。</p>
<p>给浏览器显式的指定代理，需要手动修改浏览器或操作系统相关设置，或者指定 PAC（Proxy Auto-Configuration，自动配置代理）文件自动设置，还有些浏览器支持 WPAD（Web Proxy Autodiscovery Protocol，Web 代理自动发现协议）。显式指定浏览器代理这种方式一般称之为正向代理，浏览器启用正向代理后，会对 HTTP 请求报文做一些修改，来规避老旧代理服务器的一些问题.</p>
<p>还有一种情况是访问 A 网站时，实际上访问的是代理，代理收到请求报文后，再向真正提供服务的服务器发起请求，并将响应转发给浏览器。这种情况一般被称之为反向代理，它可以用来隐藏服务器 IP 及端口。一般使用反向代理后，需要通过修改 DNS 让域名解析到代理服务器 IP，这时浏览器无法察觉到真正服务器的存在，当然也就不需要修改配置了。反向代理是 Web 系统最为常见的一种部署方式.</p>
<p>但是，使用我们这个代理服务后，HTTPS 网站完全无法访问，这是为什么呢？答案很简单，这个代理提供的是 HTTP 服务，根本没办法承载 HTTPS 服务。那么是否把这个代理改为 HTTPS 就可以了呢？显然也不可以，因为这种代理的本质是中间人，而 HTTPS 网站的证书认证机制是中间人劫持的克星。普通的 HTTPS 服务中，服务端不验证客户端的证书，中间人可以作为客户端与服务端成功完成 TLS 握手；但是中间人没有证书私钥，无论如何也无法伪造成服务端跟客户端建立 TLS 连接。当然如果你拥有证书私钥，代理证书对应的 HTTPS 网站当然就没问题了。</p>
<h2 id="隧道代理"><a href="#隧道代理" class="headerlink" title="隧道代理"></a>隧道代理</h2><p>第二种 Web 代理的原理也很简单：</p>
<blockquote>
<p>HTTP 客户端通过 CONNECT 方法请求隧道代理创建一条到达任意目的服务器和端口的 TCP 连接，并对客户端和服务器之间的后继数据进行盲转发。</p>
</blockquote>
<img src="/blogwebpage/images/iOS/web_proxy_2.jpeg" class="" title="web_proxy_2">

<p>假如我通过代理访问 A 网站，浏览器首先通过 CONNECT 请求，让代理创建一条到 A 网站的 TCP 连接；一旦 TCP 连接建好，代理无脑转发后续流量即可。所以这种代理，理论上适用于任意基于 TCP 的应用层协议，HTTPS 网站使用的 TLS 协议当然也可以。这也是这种代理为什么被称为隧道的原因。对于 HTTPS 来说，客户端透过代理直接跟服务端进行 TLS 握手协商密钥，所以依然是安全的</p>
<p>浏览器与代理进行 TCP 握手之后，发起了 CONNECT 请求，报文起始行如下：</p>
<blockquote>
<p>CONNECT wangkejie.com:443 HTTP/1.1</p>
</blockquote>
<p>对于 CONNECT 请求来说，只是用来让代理创建 TCP 连接，所以只需要提供服务器域名及端口即可，并不需要具体的资源路径。代理收到这样的请求后，需要与服务端建立 TCP 连接，并响应给浏览器这样一个 HTTP 报文：</p>
<blockquote>
<p>HTTP/1.1 200 Connection Established</p>
</blockquote>
<p>浏览器收到了这个响应报文，就可以认为到服务端的 TCP 连接已经打通，后续直接往这个 TCP 连接写协议数据即可。通过 Wireshark 的 Follow TCP Steam 功能.</p>
<p>而 CONNECT 暴露的域名和端口，对于普通的 HTTPS 请求来说，中间人一样可以拿到（IP 和端口很容易拿到，请求的域名可以通过 DNS Query 或者 TLS Client Hello 中的 Server Name Indication 拿到），所以这种方式并没有增加不安全性。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/interview/protocol.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/interview/protocol.html" class="post-title-link" itemprop="url">面向协议开发</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/%E9%9D%A2%E5%90%91%E5%8D%8F%E8%AE%AE%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">面向协议开发</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>当时，项目中有个需求让画柱状图折线图表格，无意间看到了一个非常好的 Swift 库，是安卓的 iOS 是实现版，思路清晰，建议学习。<span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2RhbmllbGdpbmRpL0NoYXJ0cw==">Charts<i class="fa fa-external-link-alt"></i></span></p>
<p>为什么我要先说这个库呢，因为我觉得它用到了面相协议的思想，比如绘制，数据, 表格等 Provider。</p>
<ul>
<li>说的好听点，就是组件化了，每个组件负责自己的事情，通过 Protocol 向外传输职责的能力.</li>
<li>还可以这么说，就是抽象类，类似于接口, 也类似于多继承。</li>
<li>面向协议其实是建立在面向对象的基础上，这些对象具有共同的行为，称之为遵守某种协议，也就是抽象出来的面相协议。</li>
<li>我不关心内部实现，我只关心行为。你可以吃饭，他也可以吃饭，但我只关心吃饭这件事儿，并不关心你们怎么吃的，吃的啥。。。 也就是组件化，你吃你的，他吃他的，你们自己实现怎么吃，我只下命令该吃饭了！</li>
</ul>
<p>引用网上说的：<br>简单来说，面向协议编程是在面向对象编程基础上演变而来，将程序设计过程中遇到的数据类型的抽取（抽象）由使用基类进行抽取改为使用协议（Java语言中的接口）进行抽取。更简单点举个栗子来说，一个猫类、一个狗类，我们很容易想到抽取一个描述动物的基类，也会有人想到抽取一个动物通用的协议，那后者就可以被叫做面向协议编程了。什么？就是这样而已？苹果官方那么正式的称Swift是一门支持面向协议编程的语言，难道就是这么简单的内容？当然不会，有过面向对象编程经验的人都会清楚，协议的使用限制很多，并不能适用于大多数情况下数据类型的抽象。而在Swift语言中，协议被赋予了更多的功能和更广阔的使用空间，在Swift 2.0中，更为协议增加了扩展功能，使其能够胜任绝大多数情况下数据类型的抽象，所以苹果开始声称Swift是一门支持面向协议编程的语言。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/interview/runloop.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/interview/runloop.html" class="post-title-link" itemprop="url">RunLoop</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/RunLoop/" itemprop="url" rel="index"><span itemprop="name">RunLoop</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="RunLoop"><a href="#RunLoop" class="headerlink" title="RunLoop"></a>RunLoop</h1><p>惯例先上文档和源码：<br><span class="exturl" data-url="aHR0cHM6Ly9vcGVuc291cmNlLmFwcGxlLmNvbS9zb3VyY2UvQ0YvQ0YtMTE1My4xOC8=">CFRunloopRef 源码<i class="fa fa-external-link-alt"></i></span><br><span class="exturl" data-url="aHR0cHM6Ly9kZXZlbG9wZXIuYXBwbGUuY29tL2xpYnJhcnkvYXJjaGl2ZS9kb2N1bWVudGF0aW9uL0NvY29hL0NvbmNlcHR1YWwvTXVsdGl0aHJlYWRpbmcvUnVuTG9vcE1hbmFnZW1lbnQvUnVuTG9vcE1hbmFnZW1lbnQuaHRtbA==">RunLoop文档<i class="fa fa-external-link-alt"></i></span></p>
<p><span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2FwcGxlL3N3aWZ0LWNvcmVsaWJzLWZvdW5kYXRpb24v">Swift-Corelibs-foundation<i class="fa fa-external-link-alt"></i></span></p>
<p><a href="./iOS/RunLoop/runloopfanyi.html">官方文档翻译</a></p>
<p>参看我之前Runloop章节，RunLoop线程是一一对应的；以及若干个Mode、若干个commonModeItem，还有一个当前运行的CurrentMode。如果在RunLoop中需要切换 Mode，只能退出 Loop，再重新指定一个 Mode 进入。这样做主要是为了分隔开不同组的 Source/Timer/Observer，让其互不影响。</p>
<h2 id="CFRunLoopSource"><a href="#CFRunLoopSource" class="headerlink" title="CFRunLoopSource"></a>CFRunLoopSource</h2><p>对应CFRunLoopModeRef，其结构如下</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">__CFRunLoopSource</span> </span>&#123;</span><br><span class="line">    <span class="type">CFRuntimeBase</span> _base;</span><br><span class="line">    uint32_t _bits; <span class="comment">//用于标记Signaled状态，source0只有在被标记为Signaled状态，才会被处理</span></span><br><span class="line">    pthread_mutex_t _lock;</span><br><span class="line">    <span class="type">CFIndex</span> _order;         <span class="comment">/* immutable */</span></span><br><span class="line">    <span class="type">CFMutableBagRef</span> _runLoops;</span><br><span class="line">    union &#123;</span><br><span class="line">        <span class="type">CFRunLoopSourceContext</span> version0;     <span class="comment">/* immutable, except invalidation */</span></span><br><span class="line">        <span class="type">CFRunLoopSourceContext1</span> version1;    <span class="comment">/* immutable, except invalidation */</span></span><br><span class="line">    &#125; _context;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>Source分为Source、Observer、Timer三种，他们统称为modeItem。</p>
<p>__CFRunLoopSource是事件产生的地方。Source有两个版本：Source0 和 Source1。</p>
<ul>
<li>source0 只包含了一个回调（函数指针），source0是需要手动触发的Source，它并不能主动触发事件，必须要先把它标记为signal状态。使用时，你需要先调用 <code>CFRunLoopSourceSignal(source)</code>，将这个 Source 标记为待处理，也就是通过uint32_t _bits来实现的，只有_bits标记Signaled状态才会被处理。然后手动调用 <code>CFRunLoopWakeUp(runloop)</code> 来唤醒 RunLoop，让其处理这个事件。</li>
<li>source1 包含了一个 mach_port 和一个回调（函数指针），被用于<code>通过内核和其他线程相互发送消息</code>。这种 Source 能主动唤醒 RunLoop 的线程。简单来说就是更加偏向于底层。</li>
</ul>
<blockquote>
<p>ource1除了多个了getPort。其余的字段含义和source0相同。作用就是当source被添加到mode中的时候，从这个函数中获得具体mach_port_t。</p>
</blockquote>
<h2 id="CFRunLoopTimer"><a href="#CFRunLoopTimer" class="headerlink" title="CFRunLoopTimer"></a>CFRunLoopTimer</h2><p>对应RunLoopTimerRef，结构如下：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">__CFRunLoopTimer</span> </span>&#123;</span><br><span class="line">    <span class="type">CFRuntimeBase</span> _base;</span><br><span class="line">    uint16_t _bits;  <span class="comment">//标记fire状态</span></span><br><span class="line">    pthread_mutex_t _lock;</span><br><span class="line">    <span class="type">CFRunLoopRef</span> _runLoop;        <span class="comment">//添加该timer的runloop</span></span><br><span class="line">    <span class="type">CFMutableSetRef</span> _rlModes;     <span class="comment">//存放所有包含该timer的 mode的 modeName，意味着一个timer可能会在多个mode中存在</span></span><br><span class="line">    <span class="type">CFAbsoluteTime</span> _nextFireDate;</span><br><span class="line">    <span class="type">CFTimeInterval</span> _interval;     <span class="comment">//理想时间间隔  /* immutable */</span></span><br><span class="line">    <span class="type">CFTimeInterval</span> _tolerance;    <span class="comment">//时间偏差      /* mutable */</span></span><br><span class="line">    uint64_t _fireTSR;          <span class="comment">/* TSR units */</span></span><br><span class="line">    <span class="type">CFIndex</span> _order;         <span class="comment">/* immutable */</span></span><br><span class="line">    <span class="type">CFRunLoopTimerCallBack</span> _callout;    <span class="comment">/* immutable */</span></span><br><span class="line">    <span class="type">CFRunLoopTimerContext</span> _context; <span class="comment">/* immutable, except invalidation */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>它和 NSTimer 是toll-free bridged 的 , <code>根据上面的分析t一个timer可能会在多个mode中存在。</code></p>
<h2 id="CFRunLoopObserver"><a href="#CFRunLoopObserver" class="headerlink" title="CFRunLoopObserver"></a>CFRunLoopObserver</h2><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">__CFRunLoopObserver</span> </span>&#123;</span><br><span class="line">    <span class="type">CFRuntimeBase</span> _base;</span><br><span class="line">    pthread_mutex_t _lock;</span><br><span class="line">    <span class="type">CFRunLoopRef</span> _runLoop;</span><br><span class="line">    <span class="type">CFIndex</span> _rlCount;</span><br><span class="line">    <span class="type">CFOptionFlags</span> _activities;      <span class="comment">/* immutable */</span></span><br><span class="line">    <span class="type">CFIndex</span> _order;         <span class="comment">/* immutable */</span></span><br><span class="line">    <span class="type">CFRunLoopObserverCallBack</span> _callout; <span class="comment">/* immutable  设置回调函数*/</span></span><br><span class="line">    <span class="type">CFRunLoopObserverContext</span> _context;  <span class="comment">/* immutable, except invalidation */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>CFRunLoopObserver是观察者，可以观察RunLoop的各种状态，每个 Observer 都包含了一个回调（也就是上面的CFRunLoopObserverCallBack函数指针），当 RunLoop 的状态发生变化时，观察者就能通过回调接受到这个变化。状态定义在_CF_OPTIONS：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* Run Loop Observer Activities */</span></span><br><span class="line">typedef <span class="type">CF_OPTIONS</span>(<span class="type">CFOptionFlags</span>, <span class="type">CFRunLoopActivity</span>) &#123;</span><br><span class="line">    kCFRunLoopEntry = (1UL &lt;&lt; <span class="number">0</span>), <span class="comment">//即将进入run loop</span></span><br><span class="line">    kCFRunLoopBeforeTimers = (1UL &lt;&lt; <span class="number">1</span>), <span class="comment">//即将处理timer</span></span><br><span class="line">    kCFRunLoopBeforeSources = (1UL &lt;&lt; <span class="number">2</span>),<span class="comment">//即将处理source</span></span><br><span class="line">    kCFRunLoopBeforeWaiting = (1UL &lt;&lt; <span class="number">5</span>),<span class="comment">//即将进入休眠</span></span><br><span class="line">    kCFRunLoopAfterWaiting = (1UL &lt;&lt; <span class="number">6</span>),<span class="comment">//被唤醒但是还没开始处理事件</span></span><br><span class="line">    kCFRunLoopExit = (1UL &lt;&lt; <span class="number">7</span>),<span class="comment">//run loop已经退出</span></span><br><span class="line">    kCFRunLoopAllActivities = 0x0FFFFFFFU</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>下面是回调函数的原型:</p>
<blockquote>
<p>typedef void (*CFRunLoopObserverCallBack)(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info);</p>
</blockquote>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>根据上面的数据结构，总结出如下内容。</p>
<p>一个model中有多个item，这些item由source、observe、timer组成。对于我们来讲用的最多的应该是observe和timer，常常通过回调来得知当前runloop的状态，进行来优化应用程序（比如监控在waiting状态下，这个时候做一些优化的事情）。其次设置定时器执行定时任务也是很常见的。</p>
<h1 id="CFRunloopRun（核心！！）"><a href="#CFRunloopRun（核心！！）" class="headerlink" title="__CFRunloopRun（核心！！）"></a>__CFRunloopRun（核心！！）</h1><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  运行run loop</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *  @param rl              运行的RunLoop对象</span></span><br><span class="line"><span class="comment"> *  @param rlm             运行的mode</span></span><br><span class="line"><span class="comment"> *  @param seconds         run loop超时时间</span></span><br><span class="line"><span class="comment"> *  @param stopAfterHandle true:run loop处理完事件就退出  false:一直运行直到超时或者被手动终止</span></span><br><span class="line"><span class="comment"> *  @param previousMode    上一次运行的mode</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *  @return 返回4种状态</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> int32_t __CFRunLoopRun(<span class="type">CFRunLoopRef</span> rl, <span class="type">CFRunLoopModeRef</span> rlm, <span class="type">CFTimeInterval</span> seconds, <span class="type">Boolean</span> stopAfterHandle, <span class="type">CFRunLoopModeRef</span> previousMode) &#123;</span><br><span class="line">    <span class="comment">//获取系统启动后的CPU运行时间，用于控制超时时间</span></span><br><span class="line">    uint64_t startTSR = mach_absolute_time();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//如果RunLoop或者mode是stop状态，则直接return，不进入循环</span></span><br><span class="line">    <span class="keyword">if</span> (__CFRunLoopIsStopped(rl)) &#123;</span><br><span class="line">        __CFRunLoopUnsetStopped(rl);</span><br><span class="line">        <span class="keyword">return</span> kCFRunLoopRunStopped;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (rlm-&gt;_stopped) &#123;</span><br><span class="line">        rlm-&gt;_stopped = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span> kCFRunLoopRunStopped;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//mach端口，在内核中，消息在端口之间传递。 初始为0</span></span><br><span class="line">    mach_port_name_t dispatchPort = <span class="type">MACH_PORT_NULL</span>;</span><br><span class="line">    <span class="comment">//判断是否为主线程</span></span><br><span class="line">    <span class="type">Boolean</span> libdispatchQSafe = pthread_main_np() &amp;&amp; ((<span class="type">HANDLE_DISPATCH_ON_BASE_INVOCATION_ONLY</span> &amp;&amp; <span class="type">NULL</span> == previousMode) || (!<span class="type">HANDLE_DISPATCH_ON_BASE_INVOCATION_ONLY</span> &amp;&amp; <span class="number">0</span> == _CFGetTSD(__CFTSDKeyIsInGCDMainQ)));</span><br><span class="line">    <span class="comment">//如果在主线程 &amp;&amp; runloop是主线程的runloop &amp;&amp; 该mode是commonMode，则给mach端口赋值为主线程收发消息的端口</span></span><br><span class="line">    <span class="keyword">if</span> (libdispatchQSafe &amp;&amp; (<span class="type">CFRunLoopGetMain</span>() == rl) &amp;&amp; <span class="type">CFSetContainsValue</span>(rl-&gt;_commonModes, rlm-&gt;_name)) dispatchPort = _dispatch_get_main_queue_port_4CF();</span><br><span class="line">    </span><br><span class="line">#<span class="keyword">if</span> <span class="type">USE_DISPATCH_SOURCE_FOR_TIMERS</span></span><br><span class="line">    mach_port_name_t modeQueuePort = <span class="type">MACH_PORT_NULL</span>;</span><br><span class="line">    <span class="keyword">if</span> (rlm-&gt;_queue) &#123;</span><br><span class="line">        <span class="comment">//mode赋值为dispatch端口_dispatch_runloop_root_queue_perform_4CF</span></span><br><span class="line">        modeQueuePort = _dispatch_runloop_root_queue_get_port_4CF(rlm-&gt;_queue);</span><br><span class="line">        <span class="keyword">if</span> (!modeQueuePort) &#123;</span><br><span class="line">            <span class="type">CRASH</span>(<span class="string">&quot;Unable to get port for run loop mode queue (%d)&quot;</span>, -<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">#endif</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//GCD管理的定时器，用于实现runloop超时机制</span></span><br><span class="line">    dispatch_source_t timeout_timer = <span class="type">NULL</span>;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">__timeout_context</span> *<span class="title">timeout_context</span> = (<span class="title">struct</span> <span class="title">__timeout_context</span> *)<span class="title">malloc</span>(<span class="title">sizeof</span>(*<span class="title">timeout_context</span>));</span></span><br><span class="line"><span class="class">    </span></span><br><span class="line"><span class="class">    //立即超时</span></span><br><span class="line"><span class="class">    <span class="title">if</span> (<span class="title">seconds</span> &lt;= 0.0) </span>&#123; <span class="comment">// instant timeout</span></span><br><span class="line">        seconds = <span class="number">0.0</span>;</span><br><span class="line">        timeout_context-&gt;termTSR = 0ULL;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//seconds为超时时间，超时时执行__CFRunLoopTimeout函数</span></span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (seconds &lt;= <span class="type">TIMER_INTERVAL_LIMIT</span>) &#123;</span><br><span class="line">        dispatch_queue_t queue = dispatch_get_global_queue(<span class="type">DISPATCH_QUEUE_PRIORITY_HIGH</span>, <span class="type">DISPATCH_QUEUE_OVERCOMMIT</span>);</span><br><span class="line">        timeout_timer = dispatch_source_create(<span class="type">DISPATCH_SOURCE_TYPE_TIMER</span>, <span class="number">0</span>, <span class="number">0</span>, queue);</span><br><span class="line">        dispatch_retain(timeout_timer);</span><br><span class="line">        timeout_context-&gt;ds = timeout_timer;</span><br><span class="line">        timeout_context-&gt;rl = (<span class="type">CFRunLoopRef</span>)<span class="type">CFRetain</span>(rl);</span><br><span class="line">        timeout_context-&gt;termTSR = startTSR + __CFTimeIntervalToTSR(seconds);</span><br><span class="line">        dispatch_set_context(timeout_timer, timeout_context); <span class="comment">// source gets ownership of context</span></span><br><span class="line">        dispatch_source_set_event_handler_f(timeout_timer, __CFRunLoopTimeout);</span><br><span class="line">        dispatch_source_set_cancel_handler_f(timeout_timer, __CFRunLoopTimeoutCancel);</span><br><span class="line">        uint64_t ns_at = (uint64_t)((__CFTSRToTimeInterval(startTSR) + seconds) * 1000000000ULL);</span><br><span class="line">        dispatch_source_set_timer(timeout_timer, dispatch_time(<span class="number">1</span>, ns_at), <span class="type">DISPATCH_TIME_FOREVER</span>, 1000ULL);</span><br><span class="line">        dispatch_resume(timeout_timer);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//永不超时</span></span><br><span class="line">    <span class="keyword">else</span> &#123; <span class="comment">// infinite timeout</span></span><br><span class="line">        seconds = <span class="number">9999999999.0</span>;</span><br><span class="line">        timeout_context-&gt;termTSR = <span class="type">UINT64_MAX</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//标志位默认为true</span></span><br><span class="line">    <span class="type">Boolean</span> didDispatchPortLastTime = <span class="literal">true</span>;</span><br><span class="line">    <span class="comment">//记录最后runloop状态，用于return</span></span><br><span class="line">    int32_t retVal = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        <span class="comment">//初始化一个存放内核消息的缓冲池</span></span><br><span class="line">        uint8_t msg_buffer[<span class="number">3</span> * <span class="number">1024</span>];</span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_MACOSX</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED_MINI</span></span><br><span class="line">        mach_msg_header_t *msg = <span class="type">NULL</span>;</span><br><span class="line">        mach_port_t livePort = <span class="type">MACH_PORT_NULL</span>;</span><br><span class="line">#elif <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">        <span class="type">HANDLE</span> livePort = <span class="type">NULL</span>;</span><br><span class="line">        <span class="type">Boolean</span> windowsMessageReceived = <span class="literal">false</span>;</span><br><span class="line">#endif</span><br><span class="line">        <span class="comment">//取所有需要监听的port</span></span><br><span class="line">        __CFPortSet waitSet = rlm-&gt;_portSet;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//设置RunLoop为可以被唤醒状态</span></span><br><span class="line">        __CFRunLoopUnsetIgnoreWakeUps(rl);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//2.通知observer，即将触发timer回调，处理timer事件</span></span><br><span class="line">        <span class="keyword">if</span> (rlm-&gt;_observerMask &amp; kCFRunLoopBeforeTimers) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeTimers);</span><br><span class="line">        <span class="comment">//3.通知observer，即将触发Source0回调</span></span><br><span class="line">        <span class="keyword">if</span> (rlm-&gt;_observerMask &amp; kCFRunLoopBeforeSources) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeSources);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//执行加入当前runloop的block</span></span><br><span class="line">        __CFRunLoopDoBlocks(rl, rlm);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//4.处理source0事件</span></span><br><span class="line">        <span class="comment">//有事件处理返回true，没有事件返回false</span></span><br><span class="line">        <span class="type">Boolean</span> sourceHandledThisLoop = __CFRunLoopDoSources0(rl, rlm, stopAfterHandle);</span><br><span class="line">        <span class="keyword">if</span> (sourceHandledThisLoop) &#123;</span><br><span class="line">            <span class="comment">//执行加入当前runloop的block</span></span><br><span class="line">            __CFRunLoopDoBlocks(rl, rlm);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//如果没有Sources0事件处理 并且 没有超时，poll为false</span></span><br><span class="line">        <span class="comment">//如果有Sources0事件处理 或者 超时，poll都为true</span></span><br><span class="line">        <span class="type">Boolean</span> poll = sourceHandledThisLoop || (0ULL == timeout_context-&gt;termTSR);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//第一次do..whil循环不会走该分支，因为didDispatchPortLastTime初始化是true</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="type">MACH_PORT_NULL</span> != dispatchPort &amp;&amp; !didDispatchPortLastTime) &#123;</span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_MACOSX</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED_MINI</span></span><br><span class="line">            <span class="comment">//从缓冲区读取消息</span></span><br><span class="line">            msg = (mach_msg_header_t *)msg_buffer;</span><br><span class="line">            <span class="comment">//5.接收dispatchPort端口的消息，（接收source1事件）</span></span><br><span class="line">            <span class="keyword">if</span> (__CFRunLoopServiceMachPort(dispatchPort, &amp;msg, <span class="built_in">sizeof</span>(msg_buffer), &amp;livePort, <span class="number">0</span>)) &#123;</span><br><span class="line">                <span class="comment">//如果接收到了消息的话，前往第9步开始处理msg</span></span><br><span class="line">                goto handle_msg;</span><br><span class="line">            &#125;</span><br><span class="line">#elif <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">            <span class="keyword">if</span> (__CFRunLoopWaitForMultipleObjects(<span class="type">NULL</span>, &amp;dispatchPort, <span class="number">0</span>, <span class="number">0</span>, &amp;livePort, <span class="type">NULL</span>)) &#123;</span><br><span class="line">                goto handle_msg;</span><br><span class="line">            &#125;</span><br><span class="line">#endif</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        didDispatchPortLastTime = <span class="literal">false</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//6.通知观察者RunLoop即将进入休眠</span></span><br><span class="line">        <span class="keyword">if</span> (!poll &amp;&amp; (rlm-&gt;_observerMask &amp; kCFRunLoopBeforeWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopBeforeWaiting);</span><br><span class="line">        <span class="comment">//设置RunLoop为休眠状态</span></span><br><span class="line">        __CFRunLoopSetSleeping(rl);</span><br><span class="line">        <span class="comment">// do not do any user callouts after this point (after notifying of sleeping)</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// Must push the local-to-this-activation ports in on every loop</span></span><br><span class="line">        <span class="comment">// iteration, as this mode could be run re-entrantly and we don&#x27;t</span></span><br><span class="line">        <span class="comment">// want these ports to get serviced.</span></span><br><span class="line">        </span><br><span class="line">        __CFPortSetInsert(dispatchPort, waitSet);</span><br><span class="line">        </span><br><span class="line">        __CFRunLoopModeUnlock(rlm);</span><br><span class="line">        __CFRunLoopUnlock(rl);</span><br><span class="line">        </span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_MACOSX</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED_MINI</span></span><br><span class="line">#<span class="keyword">if</span> <span class="type">USE_DISPATCH_SOURCE_FOR_TIMERS</span></span><br><span class="line">        <span class="comment">//这里有个内循环，用于接收等待端口的消息</span></span><br><span class="line">        <span class="comment">//进入此循环后，线程进入休眠，直到收到新消息才跳出该循环，继续执行run loop</span></span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (kCFUseCollectableAllocator) &#123;</span><br><span class="line">                objc_clear_stack(<span class="number">0</span>);</span><br><span class="line">                memset(msg_buffer, <span class="number">0</span>, <span class="built_in">sizeof</span>(msg_buffer));</span><br><span class="line">            &#125;</span><br><span class="line">            msg = (mach_msg_header_t *)msg_buffer;</span><br><span class="line">            <span class="comment">//7.接收waitSet端口的消息</span></span><br><span class="line">            __CFRunLoopServiceMachPort(waitSet, &amp;msg, <span class="built_in">sizeof</span>(msg_buffer), &amp;livePort, poll ? <span class="number">0</span> : <span class="type">TIMEOUT_INFINITY</span>);</span><br><span class="line">            <span class="comment">//收到消息之后，livePort的值为msg-&gt;msgh_local_port，</span></span><br><span class="line">            <span class="keyword">if</span> (modeQueuePort != <span class="type">MACH_PORT_NULL</span> &amp;&amp; livePort == modeQueuePort) &#123;</span><br><span class="line">                <span class="comment">// Drain the internal queue. If one of the callout blocks sets the timerFired flag, break out and service the timer.</span></span><br><span class="line">                <span class="keyword">while</span> (_dispatch_runloop_root_queue_perform_4CF(rlm-&gt;_queue));</span><br><span class="line">                <span class="keyword">if</span> (rlm-&gt;_timerFired) &#123;</span><br><span class="line">                    <span class="comment">// Leave livePort as the queue port, and service timers below</span></span><br><span class="line">                    rlm-&gt;_timerFired = <span class="literal">false</span>;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">if</span> (msg &amp;&amp; msg != (mach_msg_header_t *)msg_buffer) free(msg);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// Go ahead and leave the inner loop.</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">while</span> (<span class="number">1</span>);</span><br><span class="line">#<span class="keyword">else</span></span><br><span class="line">        <span class="keyword">if</span> (kCFUseCollectableAllocator) &#123;</span><br><span class="line">            objc_clear_stack(<span class="number">0</span>);</span><br><span class="line">            memset(msg_buffer, <span class="number">0</span>, <span class="built_in">sizeof</span>(msg_buffer));</span><br><span class="line">        &#125;</span><br><span class="line">        msg = (mach_msg_header_t *)msg_buffer;</span><br><span class="line">        __CFRunLoopServiceMachPort(waitSet, &amp;msg, <span class="built_in">sizeof</span>(msg_buffer), &amp;livePort, poll ? <span class="number">0</span> : <span class="type">TIMEOUT_INFINITY</span>);</span><br><span class="line">#endif</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">#elif <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">        <span class="comment">// Here, use the app-supplied message queue mask. They will set this if they are interested in having this run loop receive windows messages.</span></span><br><span class="line">        __CFRunLoopWaitForMultipleObjects(waitSet, <span class="type">NULL</span>, poll ? <span class="number">0</span> : <span class="type">TIMEOUT_INFINITY</span>, rlm-&gt;_msgQMask, &amp;livePort, &amp;windowsMessageReceived);</span><br><span class="line">#endif</span><br><span class="line">        </span><br><span class="line">        __CFRunLoopLock(rl);</span><br><span class="line">        __CFRunLoopModeLock(rlm);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// Must remove the local-to-this-activation ports in on every loop</span></span><br><span class="line">        <span class="comment">// iteration, as this mode could be run re-entrantly and we don&#x27;t</span></span><br><span class="line">        <span class="comment">// want these ports to get serviced. Also, we don&#x27;t want them left</span></span><br><span class="line">        <span class="comment">// in there if this function returns.</span></span><br><span class="line">        </span><br><span class="line">        __CFPortSetRemove(dispatchPort, waitSet);</span><br><span class="line">        </span><br><span class="line"> </span><br><span class="line">        __CFRunLoopSetIgnoreWakeUps(rl);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// user callouts now OK again</span></span><br><span class="line">        <span class="comment">//取消runloop的休眠状态</span></span><br><span class="line">        __CFRunLoopUnsetSleeping(rl);</span><br><span class="line">        <span class="comment">//8.通知观察者runloop被唤醒</span></span><br><span class="line">        <span class="keyword">if</span> (!poll &amp;&amp; (rlm-&gt;_observerMask &amp; kCFRunLoopAfterWaiting)) __CFRunLoopDoObservers(rl, rlm, kCFRunLoopAfterWaiting);</span><br><span class="line">      </span><br><span class="line">        <span class="comment">//9.处理收到的消息</span></span><br><span class="line">    handle_msg:;</span><br><span class="line">        __CFRunLoopSetIgnoreWakeUps(rl);</span><br><span class="line">        </span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">        <span class="keyword">if</span> (windowsMessageReceived) &#123;</span><br><span class="line">            <span class="comment">// These Win32 APIs cause a callout, so make sure we&#x27;re unlocked first and relocked after</span></span><br><span class="line">            __CFRunLoopModeUnlock(rlm);</span><br><span class="line">            __CFRunLoopUnlock(rl);</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> (rlm-&gt;_msgPump) &#123;</span><br><span class="line">                rlm-&gt;_msgPump();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="type">MSG</span> msg;</span><br><span class="line">                <span class="keyword">if</span> (<span class="type">PeekMessage</span>(&amp;msg, <span class="type">NULL</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="type">PM_REMOVE</span> | <span class="type">PM_NOYIELD</span>)) &#123;</span><br><span class="line">                    <span class="type">TranslateMessage</span>(&amp;msg);</span><br><span class="line">                    <span class="type">DispatchMessage</span>(&amp;msg);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">            __CFRunLoopLock(rl);</span><br><span class="line">            __CFRunLoopModeLock(rlm);</span><br><span class="line">            sourceHandledThisLoop = <span class="literal">true</span>;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// To prevent starvation of sources other than the message queue, we check again to see if any other sources need to be serviced</span></span><br><span class="line">            <span class="comment">// Use 0 for the mask so windows messages are ignored this time. Also use 0 for the timeout, because we&#x27;re just checking to see if the things are signalled right now -- we will wait on them again later.</span></span><br><span class="line">            <span class="comment">// <span class="doctag">NOTE:</span> Ignore the dispatch source (it&#x27;s not in the wait set anymore) and also don&#x27;t run the observers here since we are polling.</span></span><br><span class="line">            __CFRunLoopSetSleeping(rl);</span><br><span class="line">            __CFRunLoopModeUnlock(rlm);</span><br><span class="line">            __CFRunLoopUnlock(rl);</span><br><span class="line">            </span><br><span class="line">            __CFRunLoopWaitForMultipleObjects(waitSet, <span class="type">NULL</span>, <span class="number">0</span>, <span class="number">0</span>, &amp;livePort, <span class="type">NULL</span>);</span><br><span class="line">            </span><br><span class="line">            __CFRunLoopLock(rl);</span><br><span class="line">            __CFRunLoopModeLock(rlm);</span><br><span class="line">            __CFRunLoopUnsetSleeping(rl);</span><br><span class="line">            <span class="comment">// If we have a new live port then it will be handled below as normal</span></span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">#endif</span><br><span class="line">        <span class="keyword">if</span> (<span class="type">MACH_PORT_NULL</span> == livePort) &#123;</span><br><span class="line">            <span class="type">CFRUNLOOP_WAKEUP_FOR_NOTHING</span>();</span><br><span class="line">            <span class="comment">// handle nothing</span></span><br><span class="line">            <span class="comment">//通过CFRunloopWake唤醒</span></span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (livePort == rl-&gt;_wakeUpPort) &#123;</span><br><span class="line">            <span class="type">CFRUNLOOP_WAKEUP_FOR_WAKEUP</span>();</span><br><span class="line">            <span class="comment">//什么都不干，跳回2重新循环</span></span><br><span class="line">            <span class="comment">// do nothing on Mac OS</span></span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">            <span class="comment">// Always reset the wake up port, or risk spinning forever</span></span><br><span class="line">            <span class="type">ResetEvent</span>(rl-&gt;_wakeUpPort);</span><br><span class="line">#endif</span><br><span class="line">        &#125;</span><br><span class="line">#<span class="keyword">if</span> <span class="type">USE_DISPATCH_SOURCE_FOR_TIMERS</span></span><br><span class="line">        <span class="comment">//如果是定时器事件</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (modeQueuePort != <span class="type">MACH_PORT_NULL</span> &amp;&amp; livePort == modeQueuePort) &#123;</span><br><span class="line">            <span class="type">CFRUNLOOP_WAKEUP_FOR_TIMER</span>();</span><br><span class="line">            <span class="comment">//9.1 处理timer事件</span></span><br><span class="line">            <span class="keyword">if</span> (!__CFRunLoopDoTimers(rl, rlm, mach_absolute_time())) &#123;</span><br><span class="line">                <span class="comment">// Re-arm the next timer, because we apparently fired early</span></span><br><span class="line">                __CFArmNextTimerInMode(rlm, rl);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">#endif</span><br><span class="line">#<span class="keyword">if</span> <span class="type">USE_MK_TIMER_TOO</span></span><br><span class="line">        <span class="comment">//如果是定时器事件</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (rlm-&gt;_timerPort != <span class="type">MACH_PORT_NULL</span> &amp;&amp; livePort == rlm-&gt;_timerPort) &#123;</span><br><span class="line">            <span class="type">CFRUNLOOP_WAKEUP_FOR_TIMER</span>();</span><br><span class="line">            <span class="comment">// On Windows, we have observed an issue where the timer port is set before the time which we requested it to be set. For example, we set the fire time to be TSR 167646765860, but it is actually observed firing at TSR 167646764145, which is 1715 ticks early. The result is that, when __CFRunLoopDoTimers checks to see if any of the run loop timers should be firing, it appears to be &#x27;too early&#x27; for the next timer, and no timers are handled.</span></span><br><span class="line">            <span class="comment">// In this case, the timer port has been automatically reset (since it was returned from MsgWaitForMultipleObjectsEx), and if we do not re-arm it, then no timers will ever be serviced again unless something adjusts the timer list (e.g. adding or removing timers). The fix for the issue is to reset the timer here if CFRunLoopDoTimers did not handle a timer itself. 9308754</span></span><br><span class="line">           <span class="comment">//9.1处理timer事件</span></span><br><span class="line">            <span class="keyword">if</span> (!__CFRunLoopDoTimers(rl, rlm, mach_absolute_time())) &#123;</span><br><span class="line">                <span class="comment">// Re-arm the next timer</span></span><br><span class="line">                __CFArmNextTimerInMode(rlm, rl);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">#endif</span><br><span class="line">        <span class="comment">//如果是dispatch到main queue的block</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (livePort == dispatchPort) &#123;</span><br><span class="line">            <span class="type">CFRUNLOOP_WAKEUP_FOR_DISPATCH</span>();</span><br><span class="line">            __CFRunLoopModeUnlock(rlm);</span><br><span class="line">            __CFRunLoopUnlock(rl);</span><br><span class="line">            _CFSetTSD(__CFTSDKeyIsInGCDMainQ, (void *)<span class="number">6</span>, <span class="type">NULL</span>);</span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">            void *msg = <span class="number">0</span>;</span><br><span class="line">#endif</span><br><span class="line">            <span class="comment">//9.2执行block</span></span><br><span class="line">            __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(msg);</span><br><span class="line">            _CFSetTSD(__CFTSDKeyIsInGCDMainQ, (void *)<span class="number">0</span>, <span class="type">NULL</span>);</span><br><span class="line">            __CFRunLoopLock(rl);</span><br><span class="line">            __CFRunLoopModeLock(rlm);</span><br><span class="line">            sourceHandledThisLoop = <span class="literal">true</span>;</span><br><span class="line">            didDispatchPortLastTime = <span class="literal">true</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="type">CFRUNLOOP_WAKEUP_FOR_SOURCE</span>();</span><br><span class="line">            <span class="comment">// Despite the name, this works for windows handles as well</span></span><br><span class="line">            <span class="type">CFRunLoopSourceRef</span> rls = __CFRunLoopModeFindSourceForMachPort(rl, rlm, livePort);</span><br><span class="line">            <span class="comment">// 有source1事件待处理</span></span><br><span class="line">            <span class="keyword">if</span> (rls) &#123;</span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_MACOSX</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED_MINI</span></span><br><span class="line">                mach_msg_header_t *reply = <span class="type">NULL</span>;</span><br><span class="line">                <span class="comment">//9.2 处理source1事件</span></span><br><span class="line">                sourceHandledThisLoop = __CFRunLoopDoSource1(rl, rlm, rls, msg, msg-&gt;msgh_size, &amp;reply) || sourceHandledThisLoop;</span><br><span class="line">                <span class="keyword">if</span> (<span class="type">NULL</span> != reply) &#123;</span><br><span class="line">                    (void)mach_msg(reply, <span class="type">MACH_SEND_MSG</span>, reply-&gt;msgh_size, <span class="number">0</span>, <span class="type">MACH_PORT_NULL</span>, <span class="number">0</span>, <span class="type">MACH_PORT_NULL</span>);</span><br><span class="line">                    <span class="type">CFAllocatorDeallocate</span>(kCFAllocatorSystemDefault, reply);</span><br><span class="line">                &#125;</span><br><span class="line">#elif <span class="type">DEPLOYMENT_TARGET_WINDOWS</span></span><br><span class="line">                sourceHandledThisLoop = __CFRunLoopDoSource1(rl, rlm, rls) || sourceHandledThisLoop;</span><br><span class="line">#endif</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">#<span class="keyword">if</span> <span class="type">DEPLOYMENT_TARGET_MACOSX</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED</span> || <span class="type">DEPLOYMENT_TARGET_EMBEDDED_MINI</span></span><br><span class="line">        <span class="keyword">if</span> (msg &amp;&amp; msg != (mach_msg_header_t *)msg_buffer) free(msg);</span><br><span class="line">#endif</span><br><span class="line">        </span><br><span class="line">        __CFRunLoopDoBlocks(rl, rlm);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (sourceHandledThisLoop &amp;&amp; stopAfterHandle) &#123;</span><br><span class="line">            <span class="comment">//进入run loop时传入的参数，处理完事件就返回</span></span><br><span class="line">            retVal = kCFRunLoopRunHandledSource;</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (timeout_context-&gt;termTSR &lt; mach_absolute_time()) &#123;</span><br><span class="line">            <span class="comment">//run loop超时</span></span><br><span class="line">            retVal = kCFRunLoopRunTimedOut;</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (__CFRunLoopIsStopped(rl)) &#123;</span><br><span class="line">            <span class="comment">//run loop被手动终止</span></span><br><span class="line">            __CFRunLoopUnsetStopped(rl);</span><br><span class="line">            retVal = kCFRunLoopRunStopped;</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (rlm-&gt;_stopped) &#123;</span><br><span class="line">            <span class="comment">//mode被终止</span></span><br><span class="line">            rlm-&gt;_stopped = <span class="literal">false</span>;</span><br><span class="line">            retVal = kCFRunLoopRunStopped;</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (__CFRunLoopModeIsEmpty(rl, rlm, previousMode)) &#123;</span><br><span class="line">            <span class="comment">//mode中没有要处理的事件</span></span><br><span class="line">            retVal = kCFRunLoopRunFinished;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//除了上面这几种情况，都继续循环</span></span><br><span class="line">    &#125; <span class="keyword">while</span> (<span class="number">0</span> == retVal);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (timeout_timer) &#123;</span><br><span class="line">        dispatch_source_cancel(timeout_timer);</span><br><span class="line">        dispatch_release(timeout_timer);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        free(timeout_context);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> retVal;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="RunLoop操作"><a href="#RunLoop操作" class="headerlink" title="RunLoop操作"></a>RunLoop操作</h2><ul>
<li>线程和 RunLoop 之间是一一对应的，其关系是保存在一个全局的 Dictionary 里。</li>
<li>线程刚创建时并没有 RunLoop（没有加到对应的runloop字典中），如果你不主动获取，那它一直都不会有。</li>
<li>RunLoop 的创建是发生在第一次获取时。一般是获取主线程的时候。</li>
<li>RunLoop 的销毁是发生在线程结束时。</li>
<li>只能在一个线程的内部获取其 RunLoop（主线程除外），否则就这个Runloop就没有注册销毁回调。这一点是根据pthread_equal(t, pthread_self())后面的代码，如果是当前线程后面才会注册销毁回调。因为上面讲过Runlopp暴露给外部的创建方式只有CFRunLoopGetMain() 和 CFRunLoopGetCurrent()两种，所以这种情况不用考虑。下面是CFRunloop.h的头文件暴露接口，可以看到获取方式只有两种。</li>
</ul>
<h1 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h1><p><span class="exturl" data-url="aHR0cHM6Ly9ibG9nLmliaXJlbWUuY29tLzIwMTUvMDUvMTgvcnVubG9vcC8=">还是YY大神的博客<i class="fa fa-external-link-alt"></i></span></p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="comment">/// 1. 通知Observers，即将进入RunLoop</span></span><br><span class="line">    <span class="comment">/// 此处有Observer会创建AutoreleasePool: _objc_autoreleasePoolPush();</span></span><br><span class="line">    <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(<span class="params">kCFRunLoopEntry</span>)</span>;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 2. 通知 Observers: 即将触发 Timer 回调。</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(<span class="params">kCFRunLoopBeforeTimers</span>)</span>;</span><br><span class="line">        <span class="comment">/// 3. 通知 Observers: 即将触发 Source (非基于port的,Source0) 回调。</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(<span class="params">kCFRunLoopBeforeSources</span>)</span>;</span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(<span class="params">block</span>)</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 4. 触发 Source0 (非基于port的) 回调。</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__(<span class="params">source0</span>)</span>;</span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(<span class="params">block</span>)</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 6. 通知Observers，即将进入休眠</span></span><br><span class="line">        <span class="comment">/// 此处有Observer释放并新建AutoreleasePool: _objc_autoreleasePoolPop(); _objc_autoreleasePoolPush();</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(<span class="params">kCFRunLoopBeforeWaiting</span>)</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 7. sleep to wait msg.</span></span><br><span class="line">        mach<span class="constructor">_msg()</span> -&gt; mach<span class="constructor">_msg_trap()</span>;</span><br><span class="line">        </span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 8. 通知Observers，线程被唤醒</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(<span class="params">kCFRunLoopAfterWaiting</span>)</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 9. 如果是被Timer唤醒的，回调Timer</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__(<span class="params">timer</span>)</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 9. 如果是被dispatch唤醒的，执行所有调用 dispatch_async 等方法放入main queue 的 block</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__(<span class="params">dispatched_block</span>)</span>;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">/// 9. 如果如果Runloop是被 Source1 (基于port的) 的事件唤醒了，处理这个事件</span></span><br><span class="line">        <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__(<span class="params">source1</span>)</span>;</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">    &#125; <span class="keyword">while</span> (...);</span><br><span class="line"> </span><br><span class="line">    <span class="comment">/// 10. 通知Observers，即将退出RunLoop</span></span><br><span class="line">    <span class="comment">/// 此处有Observer释放AutoreleasePool: _objc_autoreleasePoolPop();</span></span><br><span class="line">    <span class="constructor">__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__(<span class="params">kCFRunLoopExit</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Block"><a href="#Block" class="headerlink" title="Block"></a>Block</h2><p>在最开始介绍CFRunloop的时候就简单提了一下其中关于block的两个字段blocks_head，blocks_tail。并且也提到在runloop周期中会对此调用__CFRunLoopDoBlocks来执行加入到这个runloop的block。下面从源码来说明一下block如何与runloop结合的。</p>
<p>先来看看最基本的block_item 数据结构，特别注意这里保存了runloop的model，决定了block是否应该执行。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">_block_item</span> </span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">_block_item</span> *<span class="title">_next</span>;</span></span><br><span class="line"><span class="class">    <span class="title">CFTypeRef</span> <span class="title">_mode</span>;	// <span class="title">CFString</span> <span class="title">or</span> <span class="title">CFSet</span></span></span><br><span class="line"><span class="class">    <span class="title">void</span> (^<span class="title">_block</span>)(<span class="title">void</span>);</span></span><br><span class="line"><span class="class">&#125;;</span></span><br></pre></td></tr></table></figure>

<p>在执行block的时候会传入</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> 执行block</span></span><br><span class="line"><span class="comment"> @param rl runloop</span></span><br><span class="line"><span class="comment"> @param rlm 当前的model</span></span><br><span class="line"><span class="comment"> @return 是否执行</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="type">Boolean</span> __CFRunLoopDoBlocks(<span class="type">CFRunLoopRef</span> rl, <span class="type">CFRunLoopModeRef</span> rlm) &#123; <span class="comment">// Call with rl and rlm locked</span></span><br><span class="line">   <span class="comment">//如果头结点没有、或者model不存在则强制返回，什么也不做</span></span><br><span class="line">    <span class="keyword">if</span> (!rl-&gt;_blocks_head) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (!rlm || !rlm-&gt;_name) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="type">Boolean</span> did = <span class="literal">false</span>;<span class="comment">//记录其中一个block结点是否被执行过</span></span><br><span class="line">    <span class="comment">//取出头尾结点，并且将当前runloop保存的头尾节点置位NULL</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">_block_item</span> *<span class="title">head</span> = <span class="title">rl</span>-&gt;<span class="title">_blocks_head</span>;</span></span><br><span class="line"><span class="class">    <span class="title">struct</span> <span class="title">_block_item</span> *<span class="title">tail</span> = <span class="title">rl</span>-&gt;<span class="title">_blocks_tail</span>;</span></span><br><span class="line"><span class="class">    <span class="title">rl</span>-&gt;<span class="title">_blocks_head</span> = <span class="title">NULL</span>;</span></span><br><span class="line"><span class="class">    <span class="title">rl</span>-&gt;<span class="title">_blocks_tail</span> = <span class="title">NULL</span>;</span></span><br><span class="line"><span class="class">    //取出被标记为<span class="title">common</span>的所有<span class="title">mode</span>、及当前<span class="title">model</span>的<span class="title">name</span></span></span><br><span class="line"><span class="class">    <span class="title">CFSetRef</span> <span class="title">commonModes</span> = <span class="title">rl</span>-&gt;<span class="title">_commonModes</span>;</span></span><br><span class="line"><span class="class">    <span class="title">CFStringRef</span> <span class="title">curMode</span> = <span class="title">rlm</span>-&gt;<span class="title">_name</span>;</span></span><br><span class="line"><span class="class">    <span class="title">__CFRunLoopModeUnlock</span>(<span class="title">rlm</span>);</span></span><br><span class="line"><span class="class">    <span class="title">__CFRunLoopUnlock</span>(<span class="title">rl</span>);</span></span><br><span class="line"><span class="class">    </span></span><br><span class="line"><span class="class">    //定义两个临时变量，用于对保存<span class="title">block</span>链表的遍历</span></span><br><span class="line"><span class="class">    <span class="title">struct</span> <span class="title">_block_item</span> *<span class="title">prev</span> = <span class="title">NULL</span>;</span></span><br><span class="line"><span class="class">    <span class="title">struct</span> <span class="title">_block_item</span> *<span class="title">item</span> = <span class="title">head</span>;//记录头指针，从头部开始遍历</span></span><br><span class="line"><span class="class">    //开始遍历<span class="title">block</span>链表</span></span><br><span class="line"><span class="class">    <span class="title">while</span> (<span class="title">item</span>) </span>&#123;</span><br><span class="line">        <span class="class"><span class="keyword">struct</span> <span class="title">_block_item</span> *<span class="title">curr</span> = <span class="title">item</span>;</span></span><br><span class="line"><span class="class">        <span class="title">item</span> = <span class="title">item</span>-&gt;<span class="title">_next</span>;</span></span><br><span class="line"><span class="class">	<span class="title">Boolean</span> <span class="title">doit</span> = <span class="title">false</span>；//表示是否应该执行这个<span class="title">block</span>,注意和前面的<span class="title">did</span>区分开</span></span><br><span class="line"><span class="class">	</span></span><br><span class="line"><span class="class">	//从<span class="title">blockitem</span>结构体就知道,其中的<span class="title">_mode</span>只能是<span class="title">CFString</span> 或者<span class="title">CFSet</span></span></span><br><span class="line"><span class="class">	//如果<span class="title">block</span>结点保存的<span class="title">model</span>是<span class="title">CFString</span>类型</span></span><br><span class="line"><span class="class">	<span class="title">if</span> (<span class="title">CFStringGetTypeID</span>() == <span class="title">CFGetTypeID</span>(<span class="title">curr</span>-&gt;<span class="title">_mode</span>)) </span>&#123;</span><br><span class="line">	   <span class="comment">//是否执行block只需要满足下面三个条件中的一个</span></span><br><span class="line">	   <span class="comment">//1. blockitem 中保存的model是当前的model</span></span><br><span class="line">	   <span class="comment">//2. blockitem 中保存的model是标记为kCFRunLoopCommonModes的model</span></span><br><span class="line">	   <span class="comment">//3. 当前model保存在commonModes数组</span></span><br><span class="line">	    doit = <span class="type">CFEqual</span>(curr-&gt;_mode, curMode) || (<span class="type">CFEqual</span>(curr-&gt;_mode, kCFRunLoopCommonModes) &amp;&amp; <span class="type">CFSetContainsValue</span>(commonModes, curMode));</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">       <span class="comment">//如果block结点保存的model是CFSet类型，步骤和上面一样，等于换成了包含。</span></span><br><span class="line">	    doit = <span class="type">CFSetContainsValue</span>((<span class="type">CFSetRef</span>)curr-&gt;_mode, curMode) || (<span class="type">CFSetContainsValue</span>((<span class="type">CFSetRef</span>)curr-&gt;_mode, kCFRunLoopCommonModes) &amp;&amp; <span class="type">CFSetContainsValue</span>(commonModes, curMode));</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//如果不执行block,则直接移动当前结点，进行下一个blockitem的判断</span></span><br><span class="line">	<span class="keyword">if</span> (!doit) prev = curr;</span><br><span class="line">	<span class="keyword">if</span> (doit) &#123;</span><br><span class="line">	<span class="comment">//如果执行block,则先移动结点。</span></span><br><span class="line">	    <span class="keyword">if</span> (prev) prev-&gt;_next = item;</span><br><span class="line">	    <span class="keyword">if</span> (curr == head) head = item;</span><br><span class="line">	    <span class="keyword">if</span> (curr == tail) tail = prev;</span><br><span class="line">	   </span><br><span class="line">	    void (^block)(void) = curr-&gt;_block;</span><br><span class="line">            <span class="type">CFRelease</span>(curr-&gt;_mode);</span><br><span class="line">            free(curr);</span><br><span class="line">	    <span class="keyword">if</span> (doit) &#123;</span><br><span class="line">	    <span class="comment">//最终在这里执行block，__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__的函数原型就是调用block</span></span><br><span class="line">                __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__(block);</span><br><span class="line">	        did = <span class="literal">true</span>;</span><br><span class="line">	    &#125;</span><br><span class="line">            <span class="type">Block_release</span>(block); <span class="comment">// do this before relocking to prevent deadlocks where some yahoo wants to run the run loop reentrantly from their dealloc</span></span><br><span class="line">	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    __CFRunLoopLock(rl);</span><br><span class="line">    __CFRunLoopModeLock(rlm);</span><br><span class="line">    <span class="comment">//重建循环链表</span></span><br><span class="line">    <span class="keyword">if</span> (head) &#123;</span><br><span class="line">	tail-&gt;_next = rl-&gt;_blocks_head;</span><br><span class="line">	rl-&gt;_blocks_head = head;</span><br><span class="line">        <span class="keyword">if</span> (!rl-&gt;_blocks_tail) rl-&gt;_blocks_tail = tail;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> did;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过上面分析可以知道：</p>
<ul>
<li>block其实在runloop中通过循环链表保存的</li>
<li>如果block可以加入到多个model下面，但是执行block只有在加入的那个model下才能之后，或者加入modle用common标记</li>
<li>每次调用__CFRunLoopDoBlocks，会把加入的block遍历执行，然后重置循环链表。</li>
</ul>
<h2 id="AutoreleasePool"><a href="#AutoreleasePool" class="headerlink" title="AutoreleasePool"></a>AutoreleasePool</h2><p>App启动后，苹果在主线程 RunLoop 里注册了两个 Observer，其回调都是 _wrapRunLoopWithAutoreleasePoolHandler()。</p>
<p>第一个 Observer 监视的事件是 Entry(即将进入Loop)，其回调内会调用 _objc_autoreleasePoolPush() 创建自动释放池。其 order 是-2147483647，优先级最高，保证创建释放池发生在其他所有回调之前。</p>
<p>第二个 Observer 监视了两个事件： BeforeWaiting(准备进入休眠) 时调用_objc_autoreleasePoolPop() 和 _objc_autoreleasePoolPush() 释放旧的池并创建新池；Exit(即将退出Loop) 时调用 _objc_autoreleasePoolPop() 来释放自动释放池。这个 Observer 的 order 是 2147483647，优先级最低，保证其释放池子发生在其他所有回调之后。</p>
<p>在主线程执行的代码，通常是写在诸如事件回调、Timer回调内的。这些回调会被 RunLoop 创建好的 AutoreleasePool 环绕着，所以不会出现内存泄漏，开发者也不必显示创建 Pool 了。</p>
<h2 id="手势识别"><a href="#手势识别" class="headerlink" title="手势识别"></a>手势识别</h2><p>上面可以看到第二个observe就是_UIGestureRecognizerUpdateObserver，关于手势识别的。</p>
<p>当上面的 _UIApplicationHandleEventQueue() 识别了一个手势时，其首先会调用 Cancel 将当前的 touchesBegin/Move/End 系列回调打断。随后系统将对应的 UIGestureRecognizer 标记为待处理。</p>
<p>苹果注册了一个 Observer 监测 BeforeWaiting (Loop即将进入休眠) 事件，这个Observer的回调函数是 _UIGestureRecognizerUpdateObserver()，其内部会获取所有刚被标记为待处理的 GestureRecognizer，并执行GestureRecognizer的回调。</p>
<p>当有 UIGestureRecognizer 的变化(创建/销毁/状态改变)时，这个回调都会进行相应处理。</p>
<h2 id="界面更新"><a href="#界面更新" class="headerlink" title="界面更新"></a>界面更新</h2><p>上面可以看到第三和四个observe分别是_beforeCACommitHandler与_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv，是关于动画及界面更新的。</p>
<p>当在操作 UI 时，比如改变了 Frame、更新了 UIView/CALayer 的层次时，或者手动调用了 UIView/CALayer 的 setNeedsLayout/setNeedsDisplay方法后，这个 UIView/CALayer 就被标记为待处理，并被提交到一个全局的容器去。</p>
<p>苹果注册了一个 Observer 监听 BeforeWaiting(即将进入休眠) 和 Exit (即将退出Loop) 事件，回调去执行一个很长的函数：<br>_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv()。这个函数里会遍历所有待处理的 UIView/CAlayer 以执行实际的绘制和调整，并更新 UI 界面。</p>
<h2 id="定时器"><a href="#定时器" class="headerlink" title="定时器"></a>定时器</h2><p>上面截图中还有个timer</p>
<p>NSTimer 其实就是 CFRunLoopTimerRef，他们之间是 toll-free bridged 的。一个 NSTimer 注册到 RunLoop 后，RunLoop 会为其重复的时间点注册好事件。例如 10:00, 10:10, 10:20 这几个时间点。RunLoop为了节省资源，并不会在非常准确的时间点回调这个Timer。Timer 有个属性叫做 Tolerance (宽容度)，标示了当时间点到后，容许有多少最大误差。</p>
<p>如果某个时间点被错过了，例如执行了一个很长的任务，则那个时间点的回调也会跳过去，不会延后执行。就比如等公交，如果 10:10 时我忙着玩手机错过了那个点的公交，那我只能等 10:20 这一趟了。</p>
<h3 id="PerformSelecter"><a href="#PerformSelecter" class="headerlink" title="PerformSelecter"></a>PerformSelecter</h3><p>当调用 NSObject 的 performSelecter:afterDelay: 来实现延迟执行，实际上其内部会创建一个 Timer 并添加到当前线程的 RunLoop 中。<code>所以如果当前线程没有 RunLoop，则这个方法会失效。</code></p>
<p>当调用 performSelector:onThread: 时，实际上其会创建一个 Timer 加到对应的线程去，<code>同样的，如果对应线程没有 RunLoop 该方法也会失效。</code></p>
<h2 id="GCD"><a href="#GCD" class="headerlink" title="GCD"></a>GCD</h2><p>回到主线程<br>dispatch_async(dispatch_get_main_queue(), ^{<br>                                   &lt;##&gt;<br>                               });</p>
<h2 id="网络请求"><a href="#网络请求" class="headerlink" title="网络请求"></a>网络请求</h2><p>常使用 NSURLConnection 时，你会传入一个 Delegate，当调用了 [connection start] 后，这个 Delegate 就会不停收到事件回调。实际上，start 这个函数的内部会会获取 CurrentRunLoop，然后在其中的 DefaultMode 添加了4个 Source0 (即需要手动触发的Source)。CFMultiplexerSource 是负责各种 Delegate 回调的，CFHTTPCookieStorage 是处理各种 Cookie 的。</p>
<h1 id="Runloop在平时开发中的应用"><a href="#Runloop在平时开发中的应用" class="headerlink" title="Runloop在平时开发中的应用"></a>Runloop在平时开发中的应用</h1><ul>
<li>AFN线程保活</li>
</ul>
<p>AF希望能在后台线程接收 Delegate 回调。为此 AFNetworking 单独创建了一个线程，并在这个线程中启动了一个 RunLoop。过程在networkRequestThreadEntryPoint中，因为RunLoop 启动前内部必须要有至少一个 Timer/Observer/Source，所以 AFNetworking 在 [runLoop run] 之前先创建了一个新的 NSMachPort 添加进去了。通常情况下，调用者需要持有这个 NSMachPort (mach_port) 并在外部线程通过这个 port 发送消息到 loop 内；但此处添加 port 只是为了让 RunLoop 不至于退出，并没有用于实际的发送消息。</p>
<p>当需要这个后台线程执行任务时，AFNetworking 通过调用 [NSObject performSelector:onThread:..] 将这个任务扔到了后台线程的 RunLoop 中，具体内容对应start方法。</p>
<ul>
<li>AsyncDisplayKit</li>
</ul>
<p>ASDK 仿照 QuartzCore/UIKit 框架的模式，实现了一套类似的界面更新的机制：即在主线程的 RunLoop 中添加一个 Observer，监听了 kCFRunLoopBeforeWaiting 和 kCFRunLoopExit 事件，在收到回调时，遍历所有之前放入队列的待处理的任务，然后一一执行。</p>
<p>可以直接看源码进行分析<span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhY2Vib29rYXJjaGl2ZS9Bc3luY0Rpc3BsYXlLaXQ=">AsyncDisplayKit<i class="fa fa-external-link-alt"></i></span>，但是现在更名为<span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL3RleHR1cmVncm91cC90ZXh0dXJlLw==">Texture<i class="fa fa-external-link-alt"></i></span></p>
<h1 id="RunLoop的启动和退出"><a href="#RunLoop的启动和退出" class="headerlink" title="RunLoop的启动和退出"></a>RunLoop的启动和退出</h1><ul>
<li>启动RunLoop的三种方式<br>通过[NSRunLoop currentRunLoop]或者CFRunLoopGetCurrent()可以获取当前线程的runloop。<figure class="highlight erlang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- <span class="params">(void)</span>run;  </span><br><span class="line">- <span class="params">(void)</span>runUntilDate:<span class="params">(NSDate *)</span>limitDate；</span><br><span class="line">- <span class="params">(void)</span>runMode:<span class="params">(NSString *)</span>mode beforeDate:<span class="params">(NSDate *)</span>limitDate;</span><br></pre></td></tr></table></figure>
这三种方式无论通过哪一种方式启动runloop，如果没有<code>一个输入源或者timer</code>附加于<code>runloop</code>上，<code>runloop</code>就会立刻退出。<br>(1) 第一种方式，runloop会一直运行下去(线程常驻)，在此期间会处理来自输入源的数据，并且会在NSDefaultRunLoopMode模式下重复调用<code>runMode:beforeDate:</code>方法。<br>(2) 第二种方式，可以设置超时时间，在超时时间到达之前，runloop会一直运行，在此期间runloop会处理来自输入源的数据，并且也会在NSDefaultRunLoopMode模式下重复调用<code>runMode:beforeDate:</code>方法。<br>(3) 第三种方式，runloop会运行一次，超时时间到达或者第一个input source被处理，则runloop就会退出。<br><code>前两种启动方式会重复调用runMode:beforeDate:方法。</code></li>
</ul>
<ul>
<li>退出RunLoop的方式</li>
</ul>
<p>(1) 第一种启动方式的退出方法<br>文档说，如果想退出runloop，不应该使用第一种启动方式来启动runloop。<br>如果runloop没有input sources或者附加的timer，runloop就会退出。<br>虽然这样可以将runloop退出，但是苹果并不建议我们这么做，因为系统内部有可能会在当前线程的runloop中添加一些输入源，所以通过手动移除input source或者timer这种方式，并不能保证runloop一定会退出。<br>(2)第二种启动方式的退出方法 <code>runUntilDate:</code><br>可以通过 设置超时时间 来退出 runloop。<br>(3)第三种启动方式的退出方法 <code>runMode:beforeDate:</code><br>通过这种方式启动，runloop只会运行一次，当超时时间到达或者第一个输入源被处理，runloop就会退出。</p>
<p>如果我们想控制 runloop 的退出时机，而不是在处理完一个输入源事件之后就退出，那么就要重复调用<code>runMode:beforeDate:</code><br>具体可以参考苹果文档给出的方案，如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSRunLoop</span> *myLoop  = [<span class="built_in">NSRunLoop</span> currentRunLoop];</span><br><span class="line">myPort = (<span class="built_in">NSMachPort</span> *)[<span class="built_in">NSMachPort</span> port];</span><br><span class="line">[myLoop addPort:_port forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line"><span class="built_in">BOOL</span> isLoopRunning = <span class="literal">YES</span>; <span class="comment">// global</span></span><br><span class="line"><span class="keyword">while</span> (isLoopRunning &amp;&amp; [myLoop runMode:<span class="built_in">NSDefaultRunLoopMode</span> beforeDate:[<span class="built_in">NSDate</span> distantFuture]]);</span><br></pre></td></tr></table></figure>

<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在关闭runloop的地方</span></span><br><span class="line">- (<span class="keyword">void</span>)quitLoop</span><br><span class="line">&#123;</span><br><span class="line">    isLoopRunning = <span class="literal">NO</span>;</span><br><span class="line">    <span class="built_in">CFRunLoopStop</span>(<span class="built_in">CFRunLoopGetCurrent</span>());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>总之<br>如果不想退出runloop可以使用第一种方式启动runloop；<br>使用第二种方式启动runloop，可以通过设置超时时间来退出；<br>使用第三种方式启动runloop，可以通过设置超时时间或者使用CFRunLoopStop方法来退出。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/RunLoop/runloopfanyi.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/RunLoop/runloopfanyi.html" class="post-title-link" itemprop="url">RunLoop翻译</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:26:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:26:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/" itemprop="url" rel="index"><span itemprop="name">面试总结</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E9%9D%A2%E8%AF%95%E6%80%BB%E7%BB%93/RunLoop%E7%BF%BB%E8%AF%91/" itemprop="url" rel="index"><span itemprop="name">RunLoop翻译</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>这是一篇对Run Loop开发文档《Threading Program Guide:Run Loops》的翻译，来源于苹果开发文档。</p>
<p>Run loops 是和线程相关的基础部分。一个run loop是一个用来调度工作和协调接受的事件的循环。一个run loop的目的是有任务的时候保持线程忙碌，没有任务的时候线程休眠。</p>
<p>Runloop的管理并不是完全自动的，你必须编写线程代码在合适的时间点启动runloop，并且响应接收的事件。Cocoa和Core框架都提供了runloop对象供开发者配置和管理线程的runloop。然而你的应用显示不需要创建这些对象，app的框架在程序启动的过程中已经自动设置并且运行了在主线程的runloop。</p>
<p>下面的章节提供了更多关于run loops和怎么在应用中配置run loops的信息，更多的关于runloop 对象的信息查看NSRunLoop Class Reference和CFRunLoop Reference</p>
<h2 id="Run-Loop解析"><a href="#Run-Loop解析" class="headerlink" title="Run Loop解析"></a>Run Loop解析</h2><p>一个run loop和它的名字听起来非常相似，它是一个你的线程进入的循环，并且用户使用它运行事件处理程序来应答事件。 你的代码控制实现runloop的真正的循环部分。换句话说，你的代码提供了for或者while用来驱动run loop。在你的循环内，你使用一个run loop对象来启动事件处理代码—-这些代码能够接收事件并且调用已安装的事件处理程序。</p>
<p>runloop接收的事件来自两个不同类型的源，input source负责分发异步事件，消息通常来自其他的线程或者一个不同的应用程序。timer source 分发同步事件，这些事件发生在计划的时间点或者重复的时间间隔。两种类型的事件源都用一个应用程序特定的程序处理方式来处理到来的事件。</p>
<p>图标3-1展示了runloop和各种各样的事件源的概念结构，输入源异步地将事件发送给相应的处理程序，并且导致 runUntilDate:方法被在特定线程相关的run loop调用使得runloop终止，定时器源会给把事件传递给处理程序，但是不会导致runloop的终止。</p>
<p>图略，自己查看<br>除了处理输入源，run loops也会生成关于run loop的行为的通知，注册run-loop 观察者可以接收这些通知并且可以使用这些通知在线程上做额外的处理。你可以使用Core Foundation在线程上添加run loop观察者。</p>
<p>下面的节提供了更多关于run loop组成和run loop处理模式的信息，同样描述了runloop在处理事件的不同时刻获取到的通知。</p>
<h2 id="Run-Loop模式"><a href="#Run-Loop模式" class="headerlink" title="Run Loop模式"></a>Run Loop模式</h2><p>一个run loop模式是一个将要被监听额输入源和定时器的集合，以及等待run loop通知的观察者集合。你每次启动run loop，你显示或者隐士的指定一个“模式”来运行，在run loop的运行过程中，只有和指定模式相关的源才会被监听和分发它们的事件（相似的，只有和指定模式关联的观察者才能获得run loop运行进度的通知），和其他模式相关的输入源会将任何接收到的事件保存起来，直到后来以合适的模式运行run loop。</p>
<p>在你的代码中，你可以通过名字识别运行模式，Cocoa和Core Foundation都定义了一个默认的模式和其他几个通用的模式，可以通过字符串在代码中指定。你可以通过简单为自定义的模式指定字符串名的方式实现自定义模式。虽然你在自定义模式下赋值的名字是任意的，但是这些模式的内容却不是随意的，你必须确保为你创建的模式添加一个或多个输入源、定时器或者run loop观察者，这样自定义的模式才会可用。</p>
<p>你使用模式可以在特定run loop运行中过滤掉不想要的源的事件。大多数情况下，你会在“default”模式运行代码。一个模态的面板，然而可能运行在“modal”模式下，因为在这种模式下，只有和模态面板相关的源才能够把事件传递到线程上。（这里是Mac开发的吧，不理解） ,对于次要的线程，你可以使用自定义的模式阻止低优先级的输入源在时间要求比较严格的操作期间传递事件。</p>
<blockquote>
<p>注意:模式和事件的输入源要区别对待，模式不是事件的类型。比如：你不能使用模式去单独匹配鼠标按下事件或者单独匹配键盘事件。你可以使用模式来监听一组不同的端口（ports）,暂时挂起定时器。也可以改变正在被监控的源和run loop的观察者。</p>
</blockquote>
<p>表3-1列举了Cocoa和Core Foundationd的标准模式和使用的描述信息，name这一栏列举了在代码中指定模式所使用的常量。图略。。。</p>
<p><code>Default</code>:大多数操作都使用的模式，大多数情况下你应该在这个模式下开启run loop，配置输入源。</p>
<p><code>Connection</code>:Cocoa使用这个模式结合NSConnection对象来检查依赖。你自己几乎不会用到这种模式</p>
<p><code>Modal</code>：Cocoa使用这个模式区分发送到模态面板的事件。</p>
<p><code>Event tracking</code>:Cocoa用这个模式在鼠标拖拽和其他类型用户界面操作跟踪过程中限制输入的事件。</p>
<p><code>Common modes</code>:这是一个可以通常使用的模式的课配置的组合，和这个模式相关的输入源同样会和组里面的任意一个模式关联。对于Cocoa application，这个组默认包含了default、modal、event tracking模式，Core Foundation初始化时仅仅包含了default模式，你可以使用CFRunLoopAddCommonMode 添加自定义的模式。</p>
<h2 id="输入源"><a href="#输入源" class="headerlink" title="输入源"></a>输入源</h2><p>输入源异步的向你的线程分发事件，事件的来源取决于输入源的类型，通常是两种类型的一种，基于端口的输入源监控你的应用程序的Mach端口，自定义的输入源监控自定义事件源。就你的run loop而言，它不会关心一个输入源是自定义还是基于端口的。系统通常会实现两种输入源，你只管使用就可以了。两种输入源的唯一区别是他们的信号是怎么获得的。基于端口的源由内核发送信号，自定义的源必须手动的在其他线程发信号。</p>
<p>当你创建了一个输入源，你给它指定一种或者多种运行模式，模式决定了那些输入源在任意给定的时刻会被监视。大多数时间你在default模式下运行，但是也可以指定自定义的模式。如果一个输入源并不在当前模式的监视范围，它产生的任意事件都会被保存直到run loop运行在正确的模式。</p>
<h3 id="基于端口的源"><a href="#基于端口的源" class="headerlink" title="基于端口的源"></a>基于端口的源</h3><p>Cocoa和Core Foundation为使用端口相关对象和功能创建基于端口的输入源提供内置支持，比如在Cocoa里面，你从来不需要直接创建输入源，你只需要创建一个端口对象，调用NSPort的方法在run loop上添加端口，端口对象处理需要的输入源的创建和配置。</p>
<p>在Core Foundation，你必须手动的创建端口和run loop输入源。在创建端口和输入源的情况下，需要使用和对外不透透明的(开发文档没有描述)的类型（CFMachPortRef, CFMessagePortRef, or CFSocketRef）相关的函数创建合适的对象。</p>
<p>比如怎么创建一个和配置一个定制的基于端口的输入源，参考 7.7 配置基于端口的输入源</p>
<h3 id="自定义输入源"><a href="#自定义输入源" class="headerlink" title="自定义输入源"></a>自定义输入源</h3><p>创建一个定制的输入源，必须使用在Core Foundation中不透明类CFRunLoopSourceRef相关的函数，配置定制的输入源用到几个回调函数。Core Foundation会在不同的点调用这些函数配置源、处理到来的事件、在源从run loop移除的时候销毁源。</p>
<p>除了定义自定输入源在事件到来时的行为，你必须也定义事件的传递机制，输入源的这部分运行在一个单独的线程上，并且负责提供输入源的数据、在数据准备处理的时候发信号给输入源。事件的传递机制取决于你，但是不需要过于复杂。</p>
<p>有关如何创建自定义输入源的示例，请7.1 定义一个自定义的输入源。有关自定义输入源的参考信息，请参阅“CFRunLoopSource”。</p>
<h3 id="Cocoa执行消息选择器源–（Cocoa-Perform-Selector-Sources）"><a href="#Cocoa执行消息选择器源–（Cocoa-Perform-Selector-Sources）" class="headerlink" title="Cocoa执行消息选择器源–（Cocoa Perform Selector Sources）"></a>Cocoa执行消息选择器源–（Cocoa Perform Selector Sources）</h3><p>除了基于端口的输入源，Cocoa定义了一个自定义的输入源允许你在任意线程上执行selector的，就像基于端口的输入源，在目标线程上执行selector的请求被序列化了，减少了许多在多个方法同时执行在一个线程的情况下发生的同步问题。和基于端口不同的是，一个perform selector输入源在执行完selector后会自动把自己从run loop移除。</p>
<p>在10.5 之前的OS X上，perform selector 输入源主要给主线程发信息，在OS X10.5之后，可以给任意线程发消息。</p>
<p>当在线程上执行一个selector的时候，该线程必须有一个活跃的run loop，对于你创建的线程，这意味着一直等待到你的代码显示的开启run loop。因为主线程已经开启它的run loop了，所以程序一调用applicationDidFinishLaunching:就向该线程发出调用，run loop每进行一次循环就会处理队列化的perform selector的调用，而不是每次run loop循环处理队列中的选一个处理。</p>
<p>表3-2列举了定义在NSObject可以在其他线程上执行selecors的方法,因为这些方法定义在NSObject类里面，你可以在任何你可以访问到Objective-C对象的线程中使用，包括POSIX线程。这些方法实际上并不创建新的线程去执行selector。  </p>
<p>表略。。。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">performSelectorOnMainThread:withObject:waitUntilDone:</span><br><span class="line">performSelectorOnMainThread:withObject:waitUntilDone:modes:</span><br></pre></td></tr></table></figure>

<p>执行特定的selector在主线程的下一个run loop回路。这两个方法给你提供了选项来阻断当前线程直到selector被执行完毕。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">performSelector:onThread:withObject:waitUntilDone:</span><br><span class="line">performSelector:onThread:withObject:waitUntilDone:modes:</span><br></pre></td></tr></table></figure>

<p>执行特定的selector在任意线程上，这些线程通过NSThread对象表示。同样提供了阻断当前线程直到selector被执行。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">performSelector:withObject:afterDelay:</span><br><span class="line">performSelector:withObject:afterDelay:inModes:</span><br></pre></td></tr></table></figure>

<p>在当前线程上下一个run loop回路中执行selector，并附加了延迟选项。因为它等待下一个run loop回路到来才执行selector，这些方法从当前执行的代码中提供了一个自动的微小延迟。多个排队的selector会按照顺序一个一个的执行。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">cancelPreviousPerformRequestsWithTarget:</span></span><br><span class="line"><span class="attr">cancelPreviousPerformRequestsWithTarget:</span><span class="attr">selector:</span><span class="attr">object:</span></span><br></pre></td></tr></table></figure>

<p>让你取消一个通过performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method方法发送到当前线程的消息。</p>
<p>每个方法更多详细信息见NSObject Class Reference.</p>
<h3 id="定时器源"><a href="#定时器源" class="headerlink" title="定时器源"></a>定时器源</h3><p>定时器源在一个未来预先设置的时间同步地传递事件给你的线程，定时器也是一种线程通知自己做某些事情的实现方式。比如一个搜索框可以使用一个定时器去初始化一个自动搜索，在用户用户连续输入关键字的时间间隔大于某个数时触发搜索。延时的使用给了用户一个在搜索开始之前尽可能多的去打印期望的关键字的机会。</p>
<p>虽然定时器产生了基于时间的通知，但是一个定时器并不是真正实时机制。就像输入源一样，定时器关联了你的run loop里的特定的模式。如果一个timer并不是处于run loop当前监控的模式，定时器在你以定时器支持的模式运行run loop之前就不会启动。</p>
<p>相似的，一个定时器如果在run loop执行处理代码的过程中开启了，定时器会等到下一次run loop调用它的处理程序。如果run loop没有运行，定时器永远不会启动。</p>
<p>你可以配置定时器一次或者重复的产生事件，一个重复的定时器自动的在一个预定的启动(fire)时间开始重复调度自己，并不是从真正的定时器fire的时间开始算。比如，一个定时器被设定在特定的时间点启动而且从那以后5秒钟一次。预定的fire时间将永远会落在于原来5s的时间间隔，如果真正的启动时间延迟。如果启动的时间延迟非常多以至于定时器错过了一次或多次预定的fire时间点，定时器只会在错过的时间片段内启动一次，在错过的时间段fire后，定时器会重新设定下次预设的fire时间。</p>
<p>配置定时器更多参考 7.6 配置定时器, NSTimer Class Reference or CFRunLoopTimer Reference.</p>
<h2 id="run-loop-观察者"><a href="#run-loop-观察者" class="headerlink" title="run loop 观察者"></a>run loop 观察者</h2><p>与输入源相反，当一个合适的同步或者异步事件发生时输入源会fire.而run loop观察者在run loop本身自己执行的过程中会在一个特殊的地方fire。你可以用run loop观察者让你的线程去处理一个给定的事件或者为run loop将要进入睡眠准备线程。你同样可以将run loop观察者和run loop下面的事件关联起来。</p>
<p>run loop的入口</p>
<p>run loop将要处理一个定时器</p>
<p>run loop 将要处理一个输入源</p>
<p>run loop 将要进入睡眠</p>
<p>run loop 已经唤醒，但是还没有处理唤醒run loop的事件</p>
<p>退出run loop</p>
<p>你可以给app用 Core Foundation 添加run loop观察者，创建一个run loop观察者，你创建了一个CFRunLoopObserverRef的类型的对象，这个类型持续跟踪你自定义的回调和它关心的run loop活动部分。</p>
<p>和定时器相似，run loop观察者可以重复或者单次使用，一个单次使用的观察者会在它fire后在run loop中移除，一个重复的观察者依然依附在run loop上。单次还是重复可以在创建的时候指定。</p>
<p>有关如何创建run loop 观察者的示例，请参阅6.2 配置run loop。有关参考信息，请参阅CFRunLoopObserver。</p>
<h2 id="run-loop一些列的事件"><a href="#run-loop一些列的事件" class="headerlink" title="run loop一些列的事件"></a>run loop一些列的事件</h2><p>每次你运行run loop，你的线程的run loop会处理挂起的事件，并且会给它的观察者发送通知。处理的顺序是非常特别的，就是下面顺序。</p>
<p>1.通知观察者run loop已经进入了循环。</p>
<p>2.通知观察者所有准备就绪的定时器将要 fire</p>
<p>3.通知观察者所有非基于端口的输入源将要 fire</p>
<p>4.fire所有非基于端口的准备fire的输入源</p>
<p>5.如果一个基于端口的输入源准备好了并且等待fire。立刻fire。到第9部。</p>
<p>6.通知观察者线程将要睡眠</p>
<p>7.将线程睡眠直到下面任意一个事件发生。</p>
<p>一个事件到达了基于端口的源</p>
<p>定时器fire</p>
<p>run loop设置了到期的超时事件</p>
<p>显示的指定run loop唤醒</p>
<p>8.通知观察者线程已经唤醒。</p>
<p>9.处理挂起的事件。</p>
<p>如果一个用户定义的定时器fire。处理定时器事件并且重新启动run loop。到步骤2.</p>
<p>如果一个输入源fire，传递事件。</p>
<p>如果run loop是被显示的被唤醒，但超时事件还没有到，重新启动run loop进入步骤2.</p>
<p>10.通知观察者run loop已经退出。</p>
<p>因为观察者从定时器和输入源来的通知会在那些事件实际发生之前被传递过来，可能在事件发生的时刻和收到通知的时刻之间有间隔，如果在事件上时效性是非常严格的，你可以使用睡眠和从睡眠中醒来的通知来帮助你关联事件之间的时间。</p>
<p>因为定时器和其他的周期性的事件会在你运行run loop的时候传递，所以要避免run loop对事件传递的打断。一个经典行为：每当你通过一个循环不断的从应用程序请求事件来实现一个鼠标的跟踪程序的时候。因为你的代码是直接捕获的事件，而不是让应用程序正常的分发这些事件，活跃的定时器将在你的鼠标跟踪程序退出并将控制权返回给应用程序后失效。</p>
<p>一个run loop可以用run loop对象显示的唤醒，其他的事件同样可以使run loop唤醒。比如添加其他的非基于端口的输入源可以唤醒run loop可以使得输入源可以立即被处理，而不是等到其他事件发生的时候。</p>
<h2 id="什么时候会用一个run-loop"><a href="#什么时候会用一个run-loop" class="headerlink" title="什么时候会用一个run loop"></a>什么时候会用一个run loop</h2><p>唯一需要显示的运行一个run loop的场景是在应用程序中创建了辅助线程。应用程序主线程的run loop是基础设施的关键部分。所以app的框架提供了运行主线程run loop的代码并且自动开启。iOS的UIAppliaction的run方法（或者OS X 的NSApplication）开启一个应用程序的main loop作为一些列程序启动流程的一部分。如果你使用xcode模板工程创建应用，你应该从来不显示的调用这些例程。</p>
<p>对于辅助线程，你需要决定一个run loop是不是必要的，如果是，就配置并开启它。你并不需要在任意情况下都开启一个线程的run loop。比如：如果你使用一个线程执行某些长时间运行并且是事先确定的任务，你可以避免开启run loop。run loops的目的是为了应用在你想和线程有更多的交互的场合上的。比如：如果你想做下面的任何事情你就需要开启run loop。</p>
<p>使用端口或者自定义的输入源和其他线程通信</p>
<p>在线程上使用定时器</p>
<p>在cocoa应用中使用任意一个performSelector…方法</p>
<p>使得线程不被杀死去做周期性任务</p>
<p>如果你选择使用一个run loop，配置和创建是非常简单的。和所有的线程编程一样，你为在合适的场合下结束你的辅助线程指定计划。通常来说让线程以结束的退出（exit）的方式要比强制让线程终止的办法好。怎么配置和退出run loop的描述信息在 6. 使用run loop对象.</p>
<h2 id="使用run-loop对象"><a href="#使用run-loop对象" class="headerlink" title="使用run loop对象"></a>使用run loop对象</h2><p>一个run loop对象提供了添加输入源，定时器，观察者和运行run loop的主要接口，每一个线程都单独有一个run loop对象和它关联。在 Cocoa中这个对象是NSRunLoop类的一个实例，在低层次的应用中，是一个CFRunLoopRef类型的指针。</p>
<p>6.1 获取一个run loop对象</p>
<p>获取当前线程的run loop只需要用下面的一种方法：</p>
<p>在Cocoa应用，使用NSRunLoop类的类方法currentRunLoop返回一个NSRunLoop对象</p>
<p>使用CFRunLoopGetCurrent函数</p>
<p>虽然这两个并不是可以自由的桥接类型，但是你在必要的时候可以从一个NSRunLoop对象中获取一个CFRunLoop类型。 通过NSRunLoop的getCFRunLoop方法获得，然后传递给Core Foundation的代码。因为两个对象引用了相同的run loop，你可以根据需要随意调用。</p>
<p>6.2 配置run loop</p>
<p>当你在一个辅助线程上开启run loop之前，必须给run loop添加至少一个输入源或者一个定时器。如果一个run loop没有任何源来监控，就会立刻退出。参考Configuring Run Loop Sources</p>
<p>除了添加输入源，你可以添加run loop观察者，并且使用他们监测run loop不同阶段的操作，添加观察者要创建一个 CFRunLoopObserverRef 类型的对象，用CFRunLoopAddObserve函数添加到run loop上。观察者必须用Core Foundation创建，即使在Cocoa应用中。</p>
<p>3-1是一个绑定了观察者的线程开启它的run loop的代码。这个案例主要展示怎么创建run loop观察者，所以代码只是简单的创建了一个观察者来监控run loop的所有的活动。基本的处理程序（没有展示）简单地在处理定时器请求的时候记录了run loop的活动。</p>
<p>Listing 3-1 Creating a run loop observer</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)threadMain</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// The application uses garbage collection, so no autorelease pool is needed.</span></span><br><span class="line">    <span class="built_in">NSRunLoop</span>* myRunLoop = [<span class="built_in">NSRunLoop</span> currentRunLoop];</span><br><span class="line">    <span class="comment">// Create a run loop observer and attach it to the run loop.</span></span><br><span class="line">    <span class="built_in">CFRunLoopObserverContext</span>  context = &#123;<span class="number">0</span>, <span class="keyword">self</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>&#125;;</span><br><span class="line">    <span class="built_in">CFRunLoopObserverRef</span>    observer = <span class="built_in">CFRunLoopObserverCreate</span>(kCFAllocatorDefault,</span><br><span class="line">            kCFRunLoopAllActivities, <span class="literal">YES</span>, <span class="number">0</span>, &amp;myRunLoopObserver, &amp;context);</span><br><span class="line">    <span class="keyword">if</span> (observer)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">CFRunLoopRef</span>    cfLoop = [myRunLoop getCFRunLoop];</span><br><span class="line">        <span class="built_in">CFRunLoopAddObserver</span>(cfLoop, observer, kCFRunLoopDefaultMode);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Create and schedule the timer.</span></span><br><span class="line">    [<span class="built_in">NSTimer</span> scheduledTimerWithTimeInterval:<span class="number">0.1</span> target:<span class="keyword">self</span></span><br><span class="line">                selector:<span class="keyword">@selector</span>(doFireTimer:) userInfo:<span class="literal">nil</span> repeats:<span class="literal">YES</span>];</span><br><span class="line">    <span class="built_in">NSInteger</span>    loopCount = <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">do</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Run the run loop 10 times to let the timer fire.</span></span><br><span class="line">        [myRunLoop runUntilDate:[<span class="built_in">NSDate</span> dateWithTimeIntervalSinceNow:<span class="number">1</span>]];</span><br><span class="line">        loopCount--;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (loopCount);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当给长时间存在的线程配置run loop时，最好添加一个输入源来接收消息。即使你可以进入一个只有一个定时器的run loop，一旦定时器fire，就无效了。会导致run loop退出。绑定一个重复的定时器可以使得run loop在一个长的时间段运行。但是需要定期的触发定时器唤醒你的线程。这实际上是另一种形式的轮询。相反，一个输入源会等待事件的发生，在次之前会保持线程的休眠。</p>
<p>6.3 开启run loop</p>
<p>在应用中开启run loop仅仅对于辅助线程是必要的，run loop必须有至少一个输入源或者定时器去监控，如果一个都没有就会立刻结束。</p>
<p>下面是几种开启run loop的方法：</p>
<p>无条件的（Unconditionally）</p>
<p>带有时间限制设置的（With a set time limit）</p>
<p>在特定的模式下（In a particular mode）</p>
<p>无条件的进入run loop是最简单的选项，但是也是最不需要的。无条件的运行run loop将线程放在一个永久的循环中，对run loop本身的控制就非常少。你可以添加或者移除输入源或者定时器，但是唯一使得run loop停止的方式是杀死它，而且没有办法在定制的模式下运行run loop。</p>
<p>与其无条件启动run loop，不如给run loop设置一个超时时间运行反而更好。当你用一个超时时间值时，run loop会一直运行直到事件的到来或者分配的时间用完。如果一个事件到来了，事件就会被分发给处理程序去处理，然后run loop退出。如果分配的时间过期了，你可以简单的重启run loop或者花时间处理任何需要的事物。</p>
<p>除了设置超时事件值外，你也可以给run loop以指定的模式运行run loop，模式和超时时间值并不互斥，可以同时添加。模式限制了传递给run loop事件的输入源的类型。（详细信息1. Run Loop模式.）</p>
<p>3-2 是一个线程的主要代码结构，关键部分是这个案例展示了run loop的基本结构，实际上你可以给run loop添加自己的输入源和定时器然后重复的从多个程序例程中调用一个来启动run loop。每次run loop例程程序返回，你检查看看是否有任何可能导致线程结束的条件出现了。这个例子用了Core Foundation run loop程序，所以它可以检查返回结果并且知道为什么run loop退出了，如果你用Cocoa，同样可以用 NSRunLoop的方法以一个相似的方式运行run loop而且不用检查返回值，在3-14.</p>
<p>Listing 3-2 Running a run loop</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">- (void)skeletonThreadMain</span><br><span class="line">&#123;</span><br><span class="line">    <span class="regexp">//</span> Set up an autorelease pool here <span class="keyword">if</span> not using garbage collection.</span><br><span class="line">    BOOL done = NO;</span><br><span class="line">    <span class="regexp">//</span> Add your sources or timers to the run loop and <span class="keyword">do</span> any other setup.</span><br><span class="line">    <span class="keyword">do</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="regexp">//</span> Start the run loop but return after each source is handled.</span><br><span class="line">        SInt32    result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, <span class="number">10</span>, YES);</span><br><span class="line">        <span class="regexp">//</span> If a source explicitly stopped the run loop, or <span class="keyword">if</span> there are no</span><br><span class="line">        <span class="regexp">//</span> sources or timers, go ahead and <span class="keyword">exit</span>.</span><br><span class="line">        <span class="keyword">if</span> ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished))</span><br><span class="line">            done = YES;</span><br><span class="line">        <span class="regexp">//</span> Check <span class="keyword">for</span> any other <span class="keyword">exit</span> conditions here and set the</span><br><span class="line">        <span class="regexp">//</span> done variable as needed.</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (!done);</span><br><span class="line">    </span><br><span class="line">    <span class="regexp">//</span> Clean up code here. Be sure to release any allocated autorelease pools.</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>递归的运行一个run loop是有可能的，换句话说，你可以在输入源或者定时器的处理程序中调用CFRunLoopRun,CFRunLoopRunInMode,或者其他的任意的NSRunLoop方法。当这样做的时候，你可以使用任何你想要的模式运行嵌套的run loop，包括外层的run loop使用的模式。</p>
<p>6.4 退出 Run Loop</p>
<p>在使得一个run loop处理事件之前有两种办法结束run loop。</p>
<p>给run loop配置一个超时时间。</p>
<p>告诉run loop停止</p>
<p>使用超时时间当然是最好的，你可以管理它。指定超时时间让run loop结束它所有的在退出之前通常进行的操作，包括给观察者发通知。</p>
<p>用CFRunLoopStop函数显示的让run loop和通过设置超时时间产生的效果是相似的。run loop会发出所有剩下run loop相关的通知然后退出，区别在于你可以在无条件启动的run loop上使用这个技术</p>
<p>虽然移除run loop的输入源和定时器同样会导致run loop退出，但是这并不是一个可靠的停止run loop的方式。有些系统程序给run loop增加输入源处理必要的事件。因为你代码可能没有意识到这些输入源的存在，它不能移除掉这些输入源，这会阻止run loop的退出。</p>
<h2 id="线程安全和Run-Loop对象-7"><a href="#线程安全和Run-Loop对象-7" class="headerlink" title="线程安全和Run Loop对象 7"></a>线程安全和Run Loop对象 7</h2><p>线程安全的差异取决于你操作run loop所使用的API，在Core Foundation的函数通常是线程安全的，而且可以被任何线程调用。然而如果你在执行run loop配置的操作，尽可能的从该run loop对应的线程上操作依然是一个好的做法。</p>
<p>Cocoa的NSRunLoop类并不是像在Core Foundation中那样线程安全的，如果你使用NSRunLoop来修改你的run loop，你应该仅仅在run loop对应的那个线程上操作。添加一个输入源或者定时器给非当前线程的run loop会导致你的代码崩溃或者产生不可预测的行为。</p>
<h2 id="8-配置-Run-Loop-资源"><a href="#8-配置-Run-Loop-资源" class="headerlink" title="8. 配置 Run Loop 资源"></a>8. 配置 Run Loop 资源</h2><p>下面章节的代码是一些如何设置不同类型输入源的案例（Cocoa和Foundation）</p>
<ul>
<li>8.1 定义一个自定义的输入源</li>
</ul>
<p>创建一个自定义的输入源包含如下定义选项</p>
<p>输入源希望处理的信息</p>
<p>一个调度程序让感兴趣的客户（client）知道怎么和你的输入源取得联系</p>
<p>一个处理程序负责执行客户（client）发来的请求</p>
<p>一个取消程序让你输入源无效</p>
<p>因为你自己创建一个自定义的输入源来处理自定义的信息，实际的配置的设计是灵活的。调度程序和取消程序是关键程序，你的自定义输入源几乎总是需要的，剩下的大部分输入源行为发生在这些程序之外。比如你可以定义传递数据给你的输入源的机制和将输入源的存在传递给其他线程。</p>
<p>图3-2是一个自定义输入源配置的案例。这案例中程序的主线程维护对输入源、自定义输入源的自定义命令缓冲区、输入源所在的run loop的引用。当主线程有一个任务要交给工作线程的时候，它会向命令缓冲区发送一个命令和工作线程需要的所有开始任务所需要的信息。（因为主线程和工作线程都有访问命令缓冲区的权限，访问必须是同步的）一旦受到唤醒的命令，run loop调用输入源的处理程序来处理在命令缓冲区的命令。</p>
<p>3-2 操作一个自定义的输入源.png</p>
<p>下面的章节解释了上面图标自定义输入源的实现，和关键要实现的代码</p>
<ul>
<li>7.2 定义输入源</li>
</ul>
<p>自定义一个输入源需要用Core Foundation的代码来配置run loop资源，并且将它和run loop依附在一起。虽然基础的处理程序是C函数，但是并不排除你需要用OC或者C++来封装这些函数来实现你的代码主体。</p>
<p>图3-2中介绍的输入源使用了OC对象来管理一个命令行缓冲区，协调run loop。3-3展示的是这个对象的定义，RunLoopSource对象管理一个命令行缓冲区，用缓冲区接收其他线程的消息。3-3同样展示了RunLoopContext对象的定义，这是一个真正的用来传递一个RunLoopSource对象和run loop的引用到应用程序主线程的容器对象。</p>
<p>Listing 3-3 The custom input source object definition</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RunLoopSource</span> : <span class="title">NSObject</span></span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">CFRunLoopSourceRef</span> runLoopSource;</span><br><span class="line">    <span class="built_in">NSMutableArray</span>* commands;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="keyword">id</span>)init;</span><br><span class="line">- (<span class="keyword">void</span>)addToCurrentRunLoop;</span><br><span class="line">- (<span class="keyword">void</span>)invalidate;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Handler method</span></span><br><span class="line">- (<span class="keyword">void</span>)sourceFired;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Client interface for registering commands to process</span></span><br><span class="line">- (<span class="keyword">void</span>)addCommand:(<span class="built_in">NSInteger</span>)command withData:(<span class="keyword">id</span>)data;</span><br><span class="line">- (<span class="keyword">void</span>)fireAllCommandsOnRunLoop:(<span class="built_in">CFRunLoopRef</span>)runloop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// These are the CFRunLoopSourceRef callback functions.</span></span><br><span class="line"><span class="keyword">void</span> RunLoopSourceScheduleRoutine (<span class="keyword">void</span> *info, <span class="built_in">CFRunLoopRef</span> rl, <span class="built_in">CFStringRef</span> mode);</span><br><span class="line"><span class="keyword">void</span> RunLoopSourcePerformRoutine (<span class="keyword">void</span> *info);</span><br><span class="line"><span class="keyword">void</span> RunLoopSourceCancelRoutine (<span class="keyword">void</span> *info, <span class="built_in">CFRunLoopRef</span> rl, <span class="built_in">CFStringRef</span> mode);</span><br><span class="line"></span><br><span class="line"><span class="comment">// RunLoopContext is a container object used during registration of the input source.</span></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RunLoopContext</span> : <span class="title">NSObject</span></span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">CFRunLoopRef</span>        runLoop;</span><br><span class="line">    RunLoopSource*        source;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">readonly</span>) <span class="built_in">CFRunLoopRef</span> runLoop;</span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">readonly</span>) RunLoopSource* source;</span><br><span class="line"></span><br><span class="line">- (<span class="keyword">id</span>)initWithSource:(RunLoopSource*)src andLoop:(<span class="built_in">CFRunLoopRef</span>)loop;</span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>虽然输入源的自定义的数据是OC代码管理的，但是将输入源和run loop关联在一起的代码需要基于C的回调函数，这些函数的第一个会在你真正将run loop源和run loop绑定的时候调用，在3-4，因为输入源只有一个客户（主线程）它使用调度程序中的函数发送一个信息来将自己在那个线程的应用代理上注册自己。当代理想和输入源取得联系的时候，就会使用RunLoopContext对象来实现。</p>
<p>Listing 3-4 Scheduling a run loop source</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">RunLoopSourceScheduleRoutine</span> <span class="params">(<span class="keyword">void</span> *info, CFRunLoopRef rl, CFStringRef mode)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    RunLoopSource* obj = (RunLoopSource*)info;</span><br><span class="line">    AppDelegate*   del = [AppDelegate sharedAppDelegate];</span><br><span class="line">    RunLoopContext* theContext = [[RunLoopContext alloc] initWithSource:obj andLoop:rl];</span><br><span class="line">    [del performSelectorOnMainThread:@selector(registerSource:)</span><br><span class="line">                                withObject:theContext waitUntilDone:NO];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最重要的回调程序之一是用来在输入源收到到信号时处理自定义数据的，3-5展示了执行和RunLoopSource对象相关的回调代码。这个函数简单的转发了工作请求给sourceFired方法，这个方法会在以后处理命令缓冲区内出现的任何命令。</p>
<p>Listing 3-5 Performing work in the input source</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">RunLoopSourcePerformRoutine</span> <span class="params">(<span class="keyword">void</span> *info)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    RunLoopSource*  obj = (RunLoopSource*)info;</span><br><span class="line">    [obj sourceFired];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果你使用CFRunLoopSourceInvalidate函数将输入源移除，系统会调用输入源的取消代码。你可以用这个代码通知客户们你的输入源已经不再有效了，他们应该移除和它的所有的关联。3-6是RunLoopSource对象注册的取消回调代码。这个函数发送另一个RunLoopContext对象给应用代理，但是这次是请求代理移除run loop源的关联。</p>
<p>Listing 3-6 Invalidating an input source</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">RunLoopSourceCancelRoutine</span> <span class="params">(<span class="keyword">void</span> *info, CFRunLoopRef rl, CFStringRef mode)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    RunLoopSource* obj = (RunLoopSource*)info;</span><br><span class="line">    AppDelegate* del = [AppDelegate sharedAppDelegate];</span><br><span class="line">    RunLoopContext* theContext = [[RunLoopContext alloc] initWithSource:obj andLoop:rl];</span><br><span class="line"></span><br><span class="line">    [del performSelectorOnMainThread:@selector(removeSource:)</span><br><span class="line">                                withObject:theContext waitUntilDone:YES];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>备注：应用程序代理的registerSource: and removeSource:方法在Coordinating with Clients of the Input Source</p>
<ul>
<li>8.3 在run loop上添加输入源</li>
</ul>
<p>3-7展示了RunLoopSource的init和addToCurrentRunLoop方法。init方法创建了必须依附到RunLoop上的CFRunLoopSourceRef非透明类型对象，它通过传递RunLoopSource对象本身作为上下文信息，所以回调程序会有指向该对象的指针。输入源的安装工作不会在工作线程调用addToCurrentRunLoop方法前进行，addToCurrentRunLoop调用时RunLoopSourceScheduleRoutine的回调函数就会被调用，一旦输入源添加到run loop，线程就可以运行它的run loop来等待事件。</p>
<p>Listing 3-7 Installing the run loop source</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">id</span>)init</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">CFRunLoopSourceContext</span>    context = &#123;<span class="number">0</span>, <span class="keyword">self</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>,</span><br><span class="line">                                        &amp;RunLoopSourceScheduleRoutine,</span><br><span class="line">                                        RunLoopSourceCancelRoutine,</span><br><span class="line">                                        RunLoopSourcePerformRoutine&#125;;</span><br><span class="line">    runLoopSource = <span class="built_in">CFRunLoopSourceCreate</span>(<span class="literal">NULL</span>, <span class="number">0</span>, &amp;context);</span><br><span class="line">    commands = [[<span class="built_in">NSMutableArray</span> alloc] init];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</span><br><span class="line">&#125;</span><br><span class="line">- (<span class="keyword">void</span>)addToCurrentRunLoop</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">CFRunLoopRef</span> runLoop = <span class="built_in">CFRunLoopGetCurrent</span>();</span><br><span class="line">    <span class="built_in">CFRunLoopAddSource</span>(runLoop, runLoopSource, kCFRunLoopDefaultMode);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>8.4 协调输入源的客户</li>
</ul>
<p>为了输入输入源起作用，你应该巧妙控制它并且在另一个线程给它发信号。输入源的要点让和它关联的线程睡眠直到有事可做。所以让其他的线程能够获得输入源的信息和并且和输入源进行通信是现实的需求。</p>
<p>一个通知输入源的客户的方式是当输入源第一次安装在run loop上的时候发送注册请求。可以为一个输入源注册多个客户，也可以简单的注册到一些中心机构，然后在把输入源给感兴趣的客户。3-8展示了应用程序代理的注册并在RunLoopSource对象的调度函数被调用时执行的注册方法，这个方法接收RunLoopSource对象提供的RunLoopContext对象，并且把它添加到源列表上，下面的代码也包含了在从run loop移除的时候如何反注册输入源。</p>
<p>Listing 3-8 Registering and removing an input source with the application delegate</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)<span class="attr">registerSource:</span>(RunLoopContext*)sourceInfo;</span><br><span class="line">&#123;</span><br><span class="line">    [sourcesToPing <span class="attr">addObject:</span>sourceInfo];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="keyword">void</span>)<span class="attr">removeSource:</span>(RunLoopContext*)sourceInfo</span><br><span class="line">&#123;</span><br><span class="line">    id    objToRemove = nil;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (RunLoopContext* context <span class="keyword">in</span> sourcesToPing)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> ([context <span class="attr">isEqual:</span>sourceInfo])</span><br><span class="line">        &#123;</span><br><span class="line">            objToRemove = context;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (objToRemove)</span><br><span class="line">        [sourcesToPing <span class="attr">removeObject:</span>objToRemove];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>回调函数调用的方法在上面的3-4和3-6</p>
<ul>
<li>8.5 给输入源发信号</li>
</ul>
<p>当一个客户把它的数据传递给输入源后，必须给输入源发信号唤醒它的run loop，给输入源发信号让run loop知道输入源已经准备好，等待处理。因为一个信号发生的时候线程可能正在休眠，你应该总是显示的唤醒run loop。如果不这样做可能会导致处理输入源的数据上产生延迟。</p>
<p>3-9展示了RunLoopSource 对象的fireCommandsOnRunLoop方法，客户在他们为输入源做好处理缓冲区数据的准备时调用这个方法。</p>
<p>Listing 3-9 Waking up the run loop</p>
<figure class="highlight erlang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- <span class="params">(void)</span>fireCommandsOnRunLoop:<span class="params">(CFRunLoopRef)</span>runloop</span><br><span class="line">&#123;</span><br><span class="line">    CFRunLoopSourceSignal<span class="params">(runLoopSource)</span>;</span><br><span class="line">    CFRunLoopWakeUp<span class="params">(runloop)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>备注：你不应该尝试通过发送自定义输入源来处理SIGHUP或其他类型的进程级信号，用于唤醒Run Loop的Core Foundation功能不是信号安全的，不应该在应用程序的信号处理程序中使用。 有关信号处理程序例程的更多信息，请参阅sigaction手册页。</p>
<ul>
<li>8.6 配置定时器</li>
</ul>
<p>要创建定时器源，你只需创建一个定时器对象并在Run Loop中调度。 在Cocoa中，您可以使用NSTimer类来创建新的定时器对象，而在Core Foundation中，您可以使用CFRunLoopTimerRef类型。 在内部，NSTimer类只是Core Foundation的扩展，它提供了一些方便的功能，例如使用相同方法创建和计划定时器的能力。</p>
<p>在Cocoa中，您可以使用以下任一类方法一次创建和调度定时器器：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">scheduledTimerWithTimeInterval:</span><span class="attr">target:</span><span class="attr">selector:</span><span class="attr">userInfo:</span><span class="attr">repeats:</span></span><br><span class="line"><span class="attr">scheduledTimerWithTimeInterval:</span><span class="attr">invocation:</span><span class="attr">repeats:</span></span><br></pre></td></tr></table></figure>
<p>这些方法创建定时器，并以默认模式（NSDefaultRunLoopMode）将其添加到当前线程的Run Loop中。 如果您想通过创建NSTimer对象然后使用NSRunLoop的addTimer：forMode：方法将其添加到运行循环中，也可以手动调度计时器。这两种技术基本上都是一样的，但是给你不同级别的控制定时器配置。 例如，如果创建定时器并手动将其添加到运行循环中，则可以使用除默认模式之外的模式来执行此操作。 清单3-10显示了如何使用这两种技术创建定时器。 第一个定时器的初始延迟为1秒，但随后每0.1秒钟定时fire。 第二个定时器在初始0.2秒延迟后开始首次fire，然后每0.2秒fire一次。</p>
<p>Listing 3-10 Creating and scheduling timers using NSTimer</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSRunLoop</span>* myRunLoop = [<span class="built_in">NSRunLoop</span> currentRunLoop];</span><br><span class="line"></span><br><span class="line"><span class="comment">// Create and schedule the first timer.</span></span><br><span class="line"><span class="built_in">NSDate</span>* futureDate = [<span class="built_in">NSDate</span> dateWithTimeIntervalSinceNow:<span class="number">1.0</span>];</span><br><span class="line"><span class="built_in">NSTimer</span>* myTimer = [[<span class="built_in">NSTimer</span> alloc] initWithFireDate:futureDate</span><br><span class="line">                        interval:<span class="number">0.1</span></span><br><span class="line">                        target:<span class="keyword">self</span></span><br><span class="line">                        selector:<span class="keyword">@selector</span>(myDoFireTimer1:)</span><br><span class="line">                        userInfo:<span class="literal">nil</span></span><br><span class="line">                        repeats:<span class="literal">YES</span>];</span><br><span class="line">[myRunLoop addTimer:myTimer forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// Create and schedule the second timer.</span></span><br><span class="line">[<span class="built_in">NSTimer</span> scheduledTimerWithTimeInterval:<span class="number">0.2</span></span><br><span class="line">                        target:<span class="keyword">self</span></span><br><span class="line">                        selector:<span class="keyword">@selector</span>(myDoFireTimer2:)</span><br><span class="line">                        userInfo:<span class="literal">nil</span></span><br><span class="line">                        repeats:<span class="literal">YES</span>];</span><br></pre></td></tr></table></figure>
<p>清单3-11显示了使用Core Foundation函数配置定时器所需的代码。 虽然此示例不会在上下文结构中传递任何用户定义的信息，但您可以使用此结构传递定时器所需的任何自定义数据。 有关此结构的内容的更多信息，请参阅CFRunLoopTimer参考中的描述。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">CFRunLoopRef</span> <span class="string">runLoop</span> <span class="string">=</span> <span class="string">CFRunLoopGetCurrent();</span></span><br><span class="line"><span class="string">CFRunLoopTimerContext</span> <span class="string">context</span> <span class="string">=</span> &#123;<span class="number">0</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>&#125;<span class="string">;</span></span><br><span class="line"><span class="string">CFRunLoopTimerRef</span> <span class="string">timer</span> <span class="string">=</span> <span class="string">CFRunLoopTimerCreate(kCFAllocatorDefault,</span> <span class="number">0.1</span><span class="string">,</span> <span class="number">0.3</span><span class="string">,</span> <span class="number">0</span><span class="string">,</span> <span class="number">0</span><span class="string">,</span></span><br><span class="line">                                        <span class="string">&amp;myCFTimerCallback,</span> <span class="string">&amp;context);</span></span><br><span class="line"></span><br><span class="line"><span class="string">CFRunLoopAddTimer(runLoop,</span> <span class="string">timer,</span> <span class="string">kCFRunLoopCommonModes);</span></span><br></pre></td></tr></table></figure>
<ul>
<li>8.7 配置基于端口的输入源</li>
</ul>
<p>Cocoa和Core Foundation都提供基于端口的对象，用于线程之间或进程之间的通信。 以下部分将介绍如何使用几种不同类型的端口设置端口通信。</p>
<ul>
<li>8.7.1 配置NSMachPort对象</li>
</ul>
<p>要建立与NSMachPort对象的本地连接，你将创建端口对象并将其添加到主线程的Run Loop中。 启动辅助线程时，将相同的对象传递给线程的入口点函数。 辅助线程可以使用相同的对象将消息发送回主线程。</p>
<ul>
<li>8.7.2 实现主线程代码</li>
</ul>
<p>清单3-12显示了启动辅助工作线程的主线程代码。 因为Cocoa框架执行了许多用于配置端口和run loop的介入步骤，所以launchThread方法明显短于其Core Foundation中等效的配置（清单3-17）;然而，两者的行为几乎相同。 一个区别是，该方法不是将本地端口的名称发送给工作线程，而是直接发送NSPort对象。</p>
<p>Listing 3-12 Main thread launch method</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)launchThread</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">NSPort</span>* myPort = [<span class="built_in">NSMachPort</span> port];</span><br><span class="line">    <span class="keyword">if</span> (myPort)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// This class handles incoming port messages.</span></span><br><span class="line">        [myPort setDelegate:<span class="keyword">self</span>];</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Install the port as an input source on the current run loop.</span></span><br><span class="line">        [[<span class="built_in">NSRunLoop</span> currentRunLoop] addPort:myPort forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Detach the thread. Let the worker release the port.</span></span><br><span class="line">        [<span class="built_in">NSThread</span> detachNewThreadSelector:<span class="keyword">@selector</span>(LaunchThreadWithPort:)</span><br><span class="line">               toTarget:[MyWorkerClass <span class="keyword">class</span>] withObject:myPort];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为了在线程之间建立一个双向通信通道，你可能希望工作线程在登录消息中将自己的本地端口发送到主线程。 接收签入消息让你的主线程知道在启动第二个线程时一切顺利，并且还可以向你发送更多消息到该线程。清单3-13显示了主线程的handlePortMessage：方法。 当数据到达线程自己的本地端口时调用此方法。 当一个签到消息到达时，该方法直接从端口消息中检索次要线程的端口，并保存以备以后使用。</p>
<p>Listing 3-13 Handling Mach port messages</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> kCheckinMessage 100</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Handle responses from the worker thread.</span></span><br><span class="line">- (<span class="keyword">void</span>)handlePortMessage:(<span class="built_in">NSPortMessage</span> *)portMessage</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">unsigned</span> <span class="keyword">int</span> message = [portMessage msgid];</span><br><span class="line">    <span class="built_in">NSPort</span>* distantPort = <span class="literal">nil</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (message == kCheckinMessage)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Get the worker thread’s communications port.</span></span><br><span class="line">        distantPort = [portMessage sendPort];</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Retain and save the worker port for later use.</span></span><br><span class="line">        [<span class="keyword">self</span> storeDistantPort:distantPort];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Handle other messages.</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>8.7.3实现次要线程代码</li>
</ul>
<p>对于辅助工作线程，你必须配置线程并使用指定的端口将信息传回主线程。</p>
<p>清单3-14显示了设置工作线程的代码。 为线程创建自动释放池后，该方法将创建一个工作对象来驱动线程执行。 工作对象的sendCheckinMessage：方法（如清单3-15所示）为工作线程创建一个本地端口，并将一个签入消息发送回主线程。</p>
<p>Listing 3-14 Launching the worker thread using Mach ports</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">+(<span class="keyword">void</span>)LaunchThreadWithPort:(<span class="keyword">id</span>)inData</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">NSAutoreleasePool</span>*  pool = [[<span class="built_in">NSAutoreleasePool</span> alloc] init];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Set up the connection between this thread and the main thread.</span></span><br><span class="line">    <span class="built_in">NSPort</span>* distantPort = (<span class="built_in">NSPort</span>*)inData;</span><br><span class="line"></span><br><span class="line">    MyWorkerClass*  workerObj = [[<span class="keyword">self</span> alloc] init];</span><br><span class="line">    [workerObj sendCheckinMessage:distantPort];</span><br><span class="line">    [distantPort release];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Let the run loop process things.</span></span><br><span class="line">    <span class="keyword">do</span></span><br><span class="line">    &#123;</span><br><span class="line">        [[<span class="built_in">NSRunLoop</span> currentRunLoop] runMode:<span class="built_in">NSDefaultRunLoopMode</span></span><br><span class="line">                            beforeDate:[<span class="built_in">NSDate</span> distantFuture]];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (![workerObj shouldExit]);</span><br><span class="line"></span><br><span class="line">    [workerObj release];</span><br><span class="line">    [pool release];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当使用NSMachPort时，本地和远程线程可以使用相同的端口对象进行线程之间的单向通信。 换句话说，由一个线程创建的本地端口对象将成为另一个线程的远程端口对象。</p>
<p>清单3-15显示了次要线程的签入例程。 该方法设置自己的本地端口用于将来的通信，然后发送一个检入消息回主线程。 该方法使用在LaunchThreadWithPort：方法中接收的端口对象作为消息的目标。</p>
<p>Listing 3-15 Sending the check-in message using Mach ports</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)sendCheckinMessage:(<span class="built_in">NSPort</span>*)outPort</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">// Retain and save the remote port for future use.</span></span><br><span class="line">    [<span class="keyword">self</span> setRemotePort:outPort];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create and configure the worker thread port.</span></span><br><span class="line">    <span class="built_in">NSPort</span>* myPort = [<span class="built_in">NSMachPort</span> port];</span><br><span class="line">    [myPort setDelegate:<span class="keyword">self</span>];</span><br><span class="line">    [[<span class="built_in">NSRunLoop</span> currentRunLoop] addPort:myPort forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create the check-in message.</span></span><br><span class="line">    <span class="built_in">NSPortMessage</span>* messageObj = [[<span class="built_in">NSPortMessage</span> alloc] initWithSendPort:outPort</span><br><span class="line">                                         receivePort:myPort components:<span class="literal">nil</span>];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (messageObj)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Finish configuring the message and send it immediately.</span></span><br><span class="line">        [messageObj setMsgId:setMsgid:kCheckinMessage];</span><br><span class="line">        [messageObj sendBeforeDate:[<span class="built_in">NSDate</span> date]];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>8.7.4 配置一个NSMessagePort对象</li>
</ul>
<p>要建立与NSMessagePort对象的本地连接，您不能简单地在线程之间传递端口对象。 远程消息端口必须以名称获取。 在Cocoa中可能需要使用特定的名称注册本地端口，然后将该名称传递给远程线程，以便它可以获取适当的端口对象进行通信。 清单3-16显示了要使用消息端口的端口创建和注册过程。</p>
<p>Listing 3-16 Registering a message port</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSPort</span>* localPort = [[<span class="built_in">NSMessagePort</span> alloc] init];</span><br><span class="line"></span><br><span class="line"><span class="comment">// Configure the object and add it to the current run loop.</span></span><br><span class="line">[localPort setDelegate:<span class="keyword">self</span>];</span><br><span class="line">[[<span class="built_in">NSRunLoop</span> currentRunLoop] addPort:localPort forMode:<span class="built_in">NSDefaultRunLoopMode</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// Register the port using a specific name. The name must be unique.</span></span><br><span class="line"><span class="built_in">NSString</span>* localPortName = [<span class="built_in">NSString</span> stringWithFormat:<span class="string">@&quot;MyPortName&quot;</span>];</span><br><span class="line">[[<span class="built_in">NSMessagePortNameServer</span> sharedInstance] registerPort:localPort</span><br><span class="line">                     name:localPortName];</span><br></pre></td></tr></table></figure>
<ul>
<li>8.7.6 Core Foundation中配置基于端口的输入源</li>
</ul>
<p>本节介绍如何使用Core Foundation在应用程序的主线程和工作线程之间设置双向通信通道。清单3-17显示了应用程序主线程调用的代码，以启动工作线程。 代码的第一件事是设置一个CFMessagePortRef opaque类型来监听来自工作线程的消息。 工作线程需要进行连接的端口名称，以便将字符串值传递给工作线程的入口点函数。 端口名称通常在当前用户上下文中是唯一的; 否则，您可能会遇到冲突。</p>
<p>Listing 3-17 ：将Core Foundation消息端口附加到新线程</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> kThreadStackSize        (8 *4096)</span></span><br><span class="line"></span><br><span class="line"><span class="function">OSStatus <span class="title">MySpawnThread</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// Create a local port for receiving responses.</span></span><br><span class="line">    CFStringRef myPortName;</span><br><span class="line">    CFMessagePortRef myPort;</span><br><span class="line">    CFRunLoopSourceRef rlSource;</span><br><span class="line">    CFMessagePortContext context = &#123;<span class="number">0</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>&#125;;</span><br><span class="line">    Boolean shouldFreeInfo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create a string with the port name.</span></span><br><span class="line">    myPortName = CFStringCreateWithFormat(<span class="literal">NULL</span>, <span class="literal">NULL</span>, CFSTR(<span class="string">&quot;com.myapp.MainThread&quot;</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create the port.</span></span><br><span class="line">    myPort = CFMessagePortCreateLocal(<span class="literal">NULL</span>,</span><br><span class="line">                myPortName,</span><br><span class="line">                &amp;MainThreadResponseHandler,</span><br><span class="line">                &amp;context,</span><br><span class="line">                &amp;shouldFreeInfo);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (myPort != <span class="literal">NULL</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// The port was successfully created.</span></span><br><span class="line">        <span class="comment">// Now create a run loop source for it.</span></span><br><span class="line">        rlSource = CFMessagePortCreateRunLoopSource(<span class="literal">NULL</span>, myPort, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (rlSource)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">// Add the source to the current run loop.</span></span><br><span class="line">            CFRunLoopAddSource(CFRunLoopGetCurrent(), rlSource, kCFRunLoopDefaultMode);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Once installed, these can be freed.</span></span><br><span class="line">            CFRelease(myPort);</span><br><span class="line">            CFRelease(rlSource);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create the thread and continue processing.</span></span><br><span class="line">    MPTaskID        taskID;</span><br><span class="line">    <span class="keyword">return</span>(MPCreateTask(&amp;ServerThreadEntryPoint,</span><br><span class="line">                    (<span class="keyword">void</span>*)myPortName,</span><br><span class="line">                    kThreadStackSize,</span><br><span class="line">                    <span class="literal">NULL</span>,</span><br><span class="line">                    <span class="literal">NULL</span>,</span><br><span class="line">                    <span class="literal">NULL</span>,</span><br><span class="line">                    <span class="number">0</span>,</span><br><span class="line">                    &amp;taskID));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在安装端口并启动线程的情况下，主线程可以在等待线程检入时继续其正常执行。当检入消息到达时，它将被分派到主线程的MainThreadResponseHandler函数，如清单3- 18。 此函数提取工作线程的端口名称，并创建未来通信的管道。</p>
<p>Listing 3-18 Receiving the checkin message</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> kCheckinMessage 100</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Main thread port message handler</span></span><br><span class="line"><span class="function">CFDataRef <span class="title">MainThreadResponseHandler</span><span class="params">(CFMessagePortRef local,</span></span></span><br><span class="line"><span class="function"><span class="params">                    SInt32 msgid,</span></span></span><br><span class="line"><span class="function"><span class="params">                    CFDataRef data,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">void</span>* info)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (msgid == kCheckinMessage)</span><br><span class="line">    &#123;</span><br><span class="line">        CFMessagePortRef messagePort;</span><br><span class="line">        CFStringRef threadPortName;</span><br><span class="line">        CFIndex bufferLength = CFDataGetLength(data);</span><br><span class="line">        UInt8* buffer = CFAllocatorAllocate(<span class="literal">NULL</span>, bufferLength, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">        CFDataGetBytes(data, CFRangeMake(<span class="number">0</span>, bufferLength), buffer);</span><br><span class="line">        threadPortName = CFStringCreateWithBytes (<span class="literal">NULL</span>, buffer, bufferLength, kCFStringEncodingASCII, FALSE);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// You must obtain a remote message port by name.</span></span><br><span class="line">        messagePort = CFMessagePortCreateRemote(<span class="literal">NULL</span>, (CFStringRef)threadPortName);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (messagePort)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">// Retain and save the thread’s comm port for future reference.</span></span><br><span class="line">            AddPortToListOfActiveThreads(messagePort);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Since the port is retained by the previous function, release</span></span><br><span class="line">            <span class="comment">// it here.</span></span><br><span class="line">            CFRelease(messagePort);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Clean up.</span></span><br><span class="line">        CFRelease(threadPortName);</span><br><span class="line">        CFAllocatorDeallocate(<span class="literal">NULL</span>, buffer);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Process other messages.</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在配置主线程之后，唯一剩下的就是新创建的工作线程创建自己的端口并签入。清单3-19显示了工作线程的入口点函数。 该函数提取主线程的端口名称，并使用它来创建一个远程连接回主线程。 该函数然后为其自身创建本地端口，将端口安装在线程的运行循环上，并向包含本地端口名称的主线程发送检入消息。</p>
<p>Listing 3-19 Setting up the thread structures</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">OSStatus <span class="title">ServerThreadEntryPoint</span><span class="params">(<span class="keyword">void</span>* param)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// Create the remote port to the main thread.</span></span><br><span class="line">    CFMessagePortRef mainThreadPort;</span><br><span class="line">    CFStringRef portName = (CFStringRef)param;</span><br><span class="line"></span><br><span class="line">    mainThreadPort = CFMessagePortCreateRemote(<span class="literal">NULL</span>, portName);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Free the string that was passed in param.</span></span><br><span class="line">    CFRelease(portName);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create a port for the worker thread.</span></span><br><span class="line">    CFStringRef myPortName = CFStringCreateWithFormat(<span class="literal">NULL</span>, <span class="literal">NULL</span>, CFSTR(<span class="string">&quot;com.MyApp.Thread-%d&quot;</span>), MPCurrentTaskID());</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Store the port in this thread’s context info for later reference.</span></span><br><span class="line">    CFMessagePortContext context = &#123;<span class="number">0</span>, mainThreadPort, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>&#125;;</span><br><span class="line">    Boolean shouldFreeInfo;</span><br><span class="line">    Boolean shouldAbort = TRUE;</span><br><span class="line"></span><br><span class="line">    CFMessagePortRef myPort = CFMessagePortCreateLocal(<span class="literal">NULL</span>,</span><br><span class="line">                myPortName,</span><br><span class="line">                &amp;ProcessClientRequest,</span><br><span class="line">                &amp;context,</span><br><span class="line">                &amp;shouldFreeInfo);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (shouldFreeInfo)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Couldn&#x27;t create a local port, so kill the thread.</span></span><br><span class="line">        MPExit(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    CFRunLoopSourceRef rlSource = CFMessagePortCreateRunLoopSource(<span class="literal">NULL</span>, myPort, <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span> (!rlSource)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// Couldn&#x27;t create a local port, so kill the thread.</span></span><br><span class="line">        MPExit(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Add the source to the current run loop.</span></span><br><span class="line">    CFRunLoopAddSource(CFRunLoopGetCurrent(), rlSource, kCFRunLoopDefaultMode);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Once installed, these can be freed.</span></span><br><span class="line">    CFRelease(myPort);</span><br><span class="line">    CFRelease(rlSource);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Package up the port name and send the check-in message.</span></span><br><span class="line">    CFDataRef returnData = nil;</span><br><span class="line">    CFDataRef outData;</span><br><span class="line">    CFIndex stringLength = CFStringGetLength(myPortName);</span><br><span class="line">    UInt8* buffer = CFAllocatorAllocate(<span class="literal">NULL</span>, stringLength, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    CFStringGetBytes(myPortName,</span><br><span class="line">                CFRangeMake(<span class="number">0</span>,stringLength),</span><br><span class="line">                kCFStringEncodingASCII,</span><br><span class="line">                <span class="number">0</span>,</span><br><span class="line">                FALSE,</span><br><span class="line">                buffer,</span><br><span class="line">                stringLength,</span><br><span class="line">                <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line">    outData = CFDataCreate(<span class="literal">NULL</span>, buffer, stringLength);</span><br><span class="line"></span><br><span class="line">    CFMessagePortSendRequest(mainThreadPort, kCheckinMessage, outData, <span class="number">0.1</span>, <span class="number">0.0</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Clean up thread data structures.</span></span><br><span class="line">    CFRelease(outData);</span><br><span class="line">    CFAllocatorDeallocate(<span class="literal">NULL</span>, buffer);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Enter the run loop.</span></span><br><span class="line">    CFRunLoopRun();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一旦进入其run loop，发送到线程端口的所有未来事件都将由ProcessClientRequest函数处理。 该功能的实现取决于线程工作的类型，此处未显示。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/RunLoop/runloopyunxing.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blogwebpage/iOS/RunLoop/runloopyunxing.html" class="post-title-link" itemprop="url">RunLoop的运行</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 11:25:39" itemprop="dateCreated datePublished" datetime="2017-09-15T11:25:39+08:00">2017-09-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/RunLoop/" itemprop="url" rel="index"><span itemprop="name">RunLoop</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/RunLoop/RunLoop%E7%9A%84%E8%BF%90%E8%A1%8C/" itemprop="url" rel="index"><span itemprop="name">RunLoop的运行</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/blogwebpage/page/2/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/blogwebpage/">1</a><a class="page-number" href="/blogwebpage/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/blogwebpage/page/4/">4</a><span class="space">&hellip;</span><a class="page-number" href="/blogwebpage/page/6/">6</a><a class="extend next" rel="next" href="/blogwebpage/page/4/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jack Wang"
      src="/blogwebpage/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Jack Wang</p>
  <div class="site-description" itemprop="description">书山有路勤为径，学海无涯苦作舟！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blogwebpage/archives/">
        
          <span class="site-state-item-count">52</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blogwebpage/categories/">
          
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blogwebpage/tags/">
          
        <span class="site-state-item-count">54</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Jack-Ving"><i class="github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjcyNzg4MTk0NUBxcS5jb20=" title="E-Mail → mailto:727881945@qq.com"><i class="envelope fa-fw"></i>E-Mail</span>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><span class="exturl" data-url="aHR0cHM6Ly9iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备16036665号-2 </span>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jack Wang</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        


  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277804316&web_id=1277804316"></script>
  </div>






      </div>
    </footer>
  </div>

  
  <script src="/blogwebpage/lib/anime.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.ui.min.js"></script>

<script src="/blogwebpage/js/utils.js"></script>

<script src="/blogwebpage/js/motion.js"></script>


<script src="/blogwebpage/js/schemes/pisces.js"></script>


<script src="/blogwebpage/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/blogwebpage/js/local-search.js"></script>













  

  
  <script src="//cdn.jsdelivr.net/npm/quicklink@1/dist/quicklink.umd.js"></script>
  <script>
      window.addEventListener('load', () => {
      quicklink({
        timeout : 3000,
        priority: true,
        ignores : [uri => uri.includes('#'),uri => uri === 'https://wangkejie.gitee.io/blogwebpage/page/3/',]
      });
      });
  </script>

</body>
</html>
